标准库 map set 删除
删除操作
有map如下:
map<int, size_t> cnt{{2,22}, {3,33}, {1,11}, {4,44};
删除方法:
| cnt.erase(3); |
删除key为3的元素,并返回删除的元素的个数 |
| cnt.erase(p); |
p为迭代器,删除p指向的元素,并返回p之后元素的迭代器 |
| cnt.erase(b, e); |
b,e为迭代器,删除b和e所表示范围的元素,返回e |
注意:当使用迭代器删除的时候,map,set,list迭代器不支持加法,减法运算,但可以++,--。
map<int, int>::const_iterator it = mp.cbegin();auto it2 = it + 2;//NG++it;//OK
小例子:
#include <iostream>#include <map>#include <set>#include <vector>#include <list>#include <algorithm>using namespace std;int main(){ map<int , int> mp{{2,22},{3,33},{1,11},{4,44}}; for(auto const &s : mp){ cout << s.first << "," << s.second << endl; } cout << "-----------------" << endl; map<int, int>::const_iterator it = mp.cbegin(); //map,set,list迭代器不支持加法,减法运算,但可以++,--。 //auto it2 = it + 2;//NG auto it2 = mp.find(2); auto rt2 = mp.erase(it, it2);//删除1,rt2指向(2,22) cout << rt2->first << ":" << rt2->second << endl; auto rt1 = mp.erase(it2);//删除2 cout << rt1->first << ":" << rt1->second << endl; auto rt = mp.erase(3);//删除3,返回值为1或者0,因为3存在所以返回1 for(auto const &s : mp){ cout << s.first << "," << s.second << endl; }}
github完整代码
c/c++ 学习互助QQ群:877684253
本人微信:xiaoshitou5854