• 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

  • 相关阅读:
    .net 调用命令行进行解压缩
    《jQuery实战》第1章 引荐JQuery
    将指定URL文件下载到指定服务器
    Oracle学习笔记
    Spring3 AOP的使用
    Field类使用以及getDeclaredFields方法
    spring 3的使用
    Json数据类型
    RotateAnimation详解
    GsonJava对象生成Json串
  • 原文地址:https://www.cnblogs.com/xiaoshiwang/p/9697756.html
Copyright © 2020-2023  润新知