当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c/c++ 标准库 map set 删除

c/c++ 标准库 map set 删除

2018年09月26日  | 移动技术网IT编程  | 我要评论

在线看凤凰卫视,nc6400拆机,跆拳道图片

标准库 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;
  }
}

c/c++ 学习互助qq群:877684253

本人微信:xiaoshitou5854

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网