设为首页 加入收藏

TOP

c/c++ 标准库 map set 删除
2018-10-21 14:12:59 】 浏览:26
Tags:c/c 标准 map set 删除

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

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++判断回文 下一篇DirectX11 With Windows SDK--20 ..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目