C++map遍历删除数据(删除被2整除的键值对)
C++使用迭代器遍历删除数据时 调用erase函数后,原先的迭代器不能使用了,故应该在之前先做处理。
以前关于遍历删除本人都是使用一个vector来存储相关的key后,然后再删除,不过这样的效率确实不高,被朋友提点有效率好点的方法后,试了下以前以为会出错的方法,也对关联类的迭代器有了进一步认识吧,对这个迭代器先做偏移,取原先迭代器的作为移除点事其实是可行的。
以下windows,linux都测试通过
/*author: Jeson Yang date: 2015.11.18 file: ****.cpp*/ #include <iostream> #include <map> using namespace std; int main() { map<int, int> *mapValue = new map<int, int>(); mapValue->insert(make_pair(2, 1)); mapValue->insert(make_pair(3, 1)); mapValue->insert(make_pair(4, 1)); for (std::map<int, int>::iterator it = mapValue->begin(); it != mapValue->end(); ) { int key = it->first; if (key % 2 == 0) { mapValue->erase(it++); } else { ++it; } } for (std::map<int, int>::iterator it = mapValue->begin(); it != mapValue->end(); ++it) { cout << it->first << " value = " << it->second << endl; } delete mapValue; mapValue = NULL; return 0; }
by:Jeson Yang