Map in C++ STL (original) (raw)

Last Updated : 11 May, 2026

Maps are associative containers that store key–value pairs in sorted order using a self-balancing Red-Black Tree. They provide efficient O(log n) time complexity for insertion, deletion, and searching operations.

#include #include using namespace std;

int main() {

// Creating an empty map
map<int, string> m1;

// Initialize map with list
map<int, string> m2 = {{1, "Geeks"},
          {2, "For"}, {3, "Geeks"}};

for (auto& p : m2)
    cout << p.first << " " <<
    p.second << endl;
return 0;

}

`

Output

1 Geeks 2 For 3 Geeks

**Explanation: Above program demonstrates how to create and initialize a map in C++ using key–value pairs. It then iterates through the map using a range-based loop and prints each key along with its corresponding value.

Syntax

The map container is defined as **std::map class templateinside the ****** header file.

map<key_type, value_type> m;

where,

Basic Operations

Basic operations on map containers are shown below:

1. Inserting Elements

#include #include using namespace std;

int main() { map<int, string> m = {{2, "For"}, {3, "Geeks"}};

// Inserting a key value pair
m.insert({1, "Geeks"});

for (auto x: m)
    cout << x.first << " " << x.second
    << endl;
return 0;

}

`

Output

1 Geeks 2 For 3 Geeks

2. Accessing Elements

#include #include using namespace std;

int main() { map<int, string> m = {{1, "Geeks"}, {2, "For"}, {3, "Geeks"}};

// Accessing elements
cout << m[1] << endl;
cout << m.at(2);

return 0;

}

`

3. Updating Elements

#include #include using namespace std;

int main() { map<int, string> m = {{1, "Geeks"}, {2, "For"}, {3, "Geeks"}};

// Updating value
m[0] = "Tweaks";
m.at(1) = "By";

cout << m[0] << endl;
cout << m.at(1);
return 0;

}

`

4. Finding Elements

#include #include using namespace std;

int main() { map<int, string> m = {{1, "Geeks"}, {2, "For"}, {3, "Geeks"}};

// Finding element with key 2
auto it = m.find(2);

if (it != m.end())
    cout << it->first << " " << it->second;
else cout << "Key not Found!";
return 0;

}

`

5. Traversing

#include #include using namespace std;

int main() { map<int, string> m = {{1, "Geeks"}, {2, "For"}, {3, "Geeks"}};

// Traversing using iterators
for (auto it = m.begin(); it != m.end(); ++it) 
    cout << it->first << " " << it->second
    << endl;

return 0;

}

`

Output

1 Geeks 2 For 3 Geeks

6. Deleting Elements

#include #include using namespace std;

int main() { map<int, string> m = {{1, "Geeks"}, {2, "For"}, {3, "Geeks"}};

// Deleting by key
m.erase(2);

// Deleting by iterator
m.erase(m.begin());

for(auto i : m)
    cout << i.first << " " << i.second
    << endl;
return 0;

}

`

Try It Yourselfredirect icon