std::map in C++ STL
The std::map container in C++ is a part of the Standard Template Library (STL). It stores key-value pairs with unique keys, where the keys are automatically sorted. Each key maps to exactly one value.
🔧 Common Operations with std::map
1. insert({key, value})
Inserts a new key-value pair if the key is not already present in the map.
std::map<int, std::string> myMap;
myMap.insert({1, "Apple"});
myMap.insert({2, "Banana"});
2. emplace(key, value)
Inserts the key-value pair more efficiently than insert() by constructing the element in-place.
myMap.emplace(3, "Cherry");
3. erase(key)
Removes the element with the specified key from the map.
myMap.erase(2);
4. clear()
Removes all key-value pairs from the map.
myMap.clear();
5. size()
Returns the number of elements in the map.
std::cout << "Size: " << myMap.size();
6. empty()
Returns true if the map is empty; otherwise, false.
if (myMap.empty()) {
std::cout << "Map is empty";
}
7. begin() / end()
begin() returns an iterator to the first key-value pair.
end() returns an iterator to one past the last element.
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
8. find(key)
Returns an iterator to the key if found; otherwise, returns end().
auto it = myMap.find(1);
if (it != myMap.end()) {
std::cout << "Found: " << it->second;
}
9. count(key)
Returns 1 if the key exists in the map; otherwise, 0.
if (myMap.count(1)) {
std::cout << "Key exists!";
}
10. at(key)
Accesses the value associated with the given key. Throws an exception if the key is not found.
try {
std::cout << myMap.at(1);
} catch (const std::out_of_range& e) {
std::cout << "Key not found!";
}