std::map删除某个或者某些元素的示例

it2025-04-21  1

#include <iostream> #include <map> #include <string> using namespace std; int main() { typedef std::map<string, int> StringIntMap; StringIntMap coll; coll["aa"] = 1; coll["bb"] = 2; coll["cc"] = 1; coll["dd"] = 2; int value = 1; //for (StringIntMap::iterator pos = coll.begin(); pos != coll.end(); ) //{ // if (pos->second == 1) // { // coll.erase(pos++); //自从c++11之前的写法 // } // else // { // ++pos; // } //} for (StringIntMap::iterator pos = coll.begin(); pos != coll.end(); ) { if (pos->second == 1) { pos = coll.erase(pos); //自从c++11开始 } else { ++pos; } } for (StringIntMap::iterator pos = coll.begin(); pos != coll.end(); ++pos) { std::cout << "key:" << pos->first << " value:" << pos->second << std::endl; } getchar(); return 0; }
最新回复(0)