How do I insert and erase elements efficiently with std::map?

In C++, the `std::map` is a sorted associative container that contains key-value pairs. It allows for efficient insertion and erasure of elements. To perform these operations efficiently, it's essential to understand the underlying structure of the `std::map`, which is typically implemented as a red-black tree.

Inserting Elements

To insert elements into a `std::map`, you can use the `insert()` function or the subscript operator (`[]`). Both methods ensure that the map maintains its order and uniqueness of keys.

Erasing Elements

To erase elements from a `std::map`, you can use the `erase()` function. This function allows you to remove elements by key or by iterators, and it also automatically adjusts the underlying tree structure.

Example

#include #include int main() { std::map myMap; // Inserting elements myMap.insert({1, "One"}); myMap[2] = "Two"; myMap.insert(std::make_pair(3, "Three")); // Displaying elements for (const auto &pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; } // Erasing an element myMap.erase(2); // removes the key-value pair with key 2 // Displaying elements after erasure std::cout << "After erase:" << std::endl; for (const auto &pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }

std::map C++ maps efficient insertion erase elements associative container