Delete map set of c/c + + standard library

Keywords: C++ github

Standard library map set delete

Delete operation

The map is as follows:

map<int, size_t> cnt{{2,22}, {3,33}, {1,11}, {4,44};

Delete method:

Delete operation type Function description
cnt.erase(3); Delete the element with key 3 and return the number of deleted elements
cnt.erase(p); P is the iterator, delete the element pointed by P, and return the iterator of the element after p
cnt.erase(b, e); b. E is the iterator, delete the elements of the range represented by B and E, and return e

Note: when using the iterator to delete, the map, set and list iterators do not support the addition and subtraction operations, but they can + + -.

map<int, int>::const_iterator it = mp.cbegin();
auto it2 = it + 2;//NG
++it;//OK

Small example:

#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 iterators do not support addition and subtraction operations, but can be + +, -.                       
  //auto it2 = it + 2;//NG                                                      
  auto it2 = mp.find(2);
  auto rt2 = mp.erase(it, it2);//Delete 1,rt2 points to (2,22)                            
  cout << rt2->first << ":" << rt2->second << endl;
  auto rt1 = mp.erase(it2);//Delete 2                                              
  cout << rt1->first << ":" << rt1->second << endl;
  auto rt = mp.erase(3);//Delete 3, return value is 1 or 0, because 3 exists, return 1              
  for(auto const &s : mp){
    cout << s.first << "," << s.second << endl;
  }
}

github full code

QQ group of mutual learning in c/c + +: 877684253

My wechat: xiaoshitou5854

Posted by bigfunkychief on Thu, 26 Dec 2019 12:00:24 -0800