C++ Map Erase Function: Usage Guide

In C++, std::map is an associative container that holds a collection of key-value pairs, where there is a mapping relationship between keys and values. The erase() function is used to remove specified elements from std::map.

The erase() function has multiple overloaded forms, with the most commonly used form being to delete the element corresponding to the specified key. An example is shown below:

std::map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "cherry"}};

// 删除键为2的元素
myMap.erase(2);

In addition to deleting individual elements, the erase() function can also take an iterator as a parameter to delete elements at a specific position. An example is shown below:

std::map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "cherry"}};

// 删除第一个元素
auto it = myMap.begin();
myMap.erase(it);

It is important to note that the erase() function returns an iterator pointing to the position after the deleted element, which can be used for further operations. If you need to delete elements within a certain range, you can use two iterators to specify the range. An example is shown below:

std::map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "cherry"}, {4, "date"}, {5, "elderberry"}};

// 删除键大于等于3小于等于4的元素
auto start = myMap.lower_bound(3);
auto end = myMap.upper_bound(4);
myMap.erase(start, end);

In general, the erase() function in std::map is used to delete elements, either based on the key or iterator, one at a time or within a specified range.

bannerAds