How to iterate through a map in C++ and delete specific…
In C++, you can use iterators to iterate through a map and delete specific elements. The specific steps are as follows:
- car
for (auto it = myMap.begin(); it != myMap.end();)
{
// 遍历的代码
}
- Delete or remove
if (条件满足)
{
myMap.erase(it++); // 先用后加,避免迭代器失效
}
else
{
++it;
}
Here is the complete sample code:
#include <iostream>
#include <map>
int main()
{
std::map<int, std::string> myMap;
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
myMap[4] = "four";
myMap[5] = "five";
// 遍历并删除特定元素
for (auto it = myMap.begin(); it != myMap.end();)
{
if (it->first == 3)
{
myMap.erase(it++); // 先用后加,避免迭代器失效
}
else
{
++it;
}
}
// 输出结果
for (const auto& pair : myMap)
{
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
When running the above code, the output will be:
1: one
2: two
4: four
5: five
Element 3 has been successfully removed.