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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM