c++ - map::erase: difference between erase by key or by iterator? -
If I want to remove an element from a map (and I probably do not care about return value other than error Checking), there are two ways I can: Erase
by key or delete
by value:
#include & lt; Iostream & gt; # Include & lt; Map & gt; using namespace std; Zero printmap (const std :: map & lt; int, double & gt; & amp; m) {for (auto kv: m) {std :: cout & lt; & Lt; '{& Lt; & Lt; Kv.first & lt; & Lt; "," & Lt; & Lt; KV.Second & lt; & Lt; '}'; } Std :: cout & lt; & Lt; '\ N'; } Int main () {std :: cout & lt; & Lt; "Erase by the Eater: \ n"; Std :: map & lt; Int, double> M1 = {{1, 1.1}, {2, 2.2}, {3, 3.3}}; PrintMap (m1); M1.erase (m1.find (2)); PrintMap (m1); Std :: cout & lt; & Lt; "Delete key: \ n"; Std :: map & lt; Int, double> M2 = {{1, 1.1}, {2, 2.2}, {3, 3.3}}; PrintMap (m2); M2.erase (2); PrintMap (m2); Return 0; }
Output:
Eraser by Etherator: {1, 1.1} {2, 2.2} {3, 3.3} {1, 1.1} {3 , 3.3} Erase by Key: {1, 1.1} {2, 2.2} {3, 3.3} {1, 1.1} {3, 3.3}
What are the two methods Completely equivalent , or any practical reason or situation, where I can choose one on another
The description of you in the scenario ( m1.erase (2);
vs. m1.erase (m1.find (2)) ;
), two methods must be completely equivalent, they are made Area or it should cost the return of those who return, although it depends on your STL implementation. An point to
zero process entry (const std :: pair & lt; int, double & gt; & amp; p) {// something to write in the file} std :: Map & lt; Int, double & gt; M1 = {{1, 1.1}, {2, 2.2}, {3, 3.3}}; Const auto = std :: find_if (m1.begin (), m1.end (), [] (const std :: pair and lt; int, double & gt; & amp; p) {return p.first & gt; 1 & amp; amp; P.second & lt; 3.0;}); If (this! = M1.end ()) {Processory (* this); M1.erase (this); }
Comments
Post a Comment