删除指定map中指定key的元素:
#include <stdio.h> #include <string> #include <map> #include <memory> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { map<int, int> dmap; dmap.insert(pair<int, int>(3, 1)); dmap.insert(pair<int, int>(4, 1)); dmap.insert(pair<int, int>(5, 1)); dmap.insert(pair<int, int>(6, 1)); int ret = dmap.erase(3); printf("ret: %d\n", ret); ret = dmap.erase(9); printf("ret: %d\n", ret); getchar(); return 0; }
ret: 1 ret: 0
删除迭代器指定的元素:
#include <stdio.h> #include <string> #include <map> #include <memory> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { map<int, int> dmap; dmap.insert(pair<int, int>(3, 1)); dmap.insert(pair<int, int>(4, 1)); dmap.insert(pair<int, int>(5, 1)); dmap.insert(pair<int, int>(6, 1)); map<int, int>::iterator iter_ret = dmap.erase(dmap.begin()); if (iter_ret != dmap.end()) printf("iter_ret->first: %d, iter_ret->second: %d\n", iter_ret->first, iter_ret->second); iter_ret = dmap.erase(dmap.begin(), dmap.begin()); if (iter_ret != dmap.end()) printf("iter_ret->first: %d, iter_ret->second: %d\n", iter_ret->first, iter_ret->second); iter_ret = dmap.erase(dmap.begin(), dmap.end()); if (iter_ret != dmap.end()) printf("iter_ret->first: %d, iter_ret->second: %d\n", iter_ret->first, iter_ret->second); else printf("damp end\n"); getchar(); return 0; }
iter_ret->first: 4, iter_ret->second: 1 iter_ret->first: 4, iter_ret->second: 1 damp end分析:erase(iter)删除迭代器指向的元素, erase(iter1, iter2)删除[iter1, iter2)区间的元素,元素不能重复删除,否则会出错,函数会返回一个指向下一个元素的迭代器