c++ - Why is Map[2] updating a wrong key data? Is this a proper way of doing this? -


#include <iostream> using namespace std;      struct ls{ bool operator()(int lhs, int rhs){ return lhs == rhs; }     };  int main(){ map<int,string,ls> m1 {{1,"a"},{2,"b"}}; map<int,string>::iterator i;  for(i=m1.begin();i!=m1.end();++i) {     cout<<i->first<<" - "<<i->second<<endl; }       //if print data here 1, "a" data present.       m1[2] = "c";       for(i=m1.begin();i!=m1.end();++i) {               cout<<i->first<<" - "<<i->second<<endl;       }  //the above statement updates m1[1] "c" though m1[2] } 

the problem not respecting contract of std::map third template argument should comparison function.

the comparison function, defaults std::less<t>, must provide total ordering on keys of std::map. purpose iso standard defines that, associative containers @ §23.2.4.3:

the phrase “equivalence of keys” means equivalence relation imposed comparison , not operator== on keys. is, 2 keys k1 , k2 considered equivalent if comparison object comp, comp(k1, k2) == false && comp(k2, k1) == false. 2 keys k1 , k2 in same container, calling comp(k1, k2) shall return same value.

now in situation define comparison lhs == rhs means that

auto b1 = ls{}(1, 2); auto b2 = ls{}(2, 1}; 

are both false, both keys considered unique key (if a not less b , b not less a a must equal b). means on map construction first pair inserted.

but m1[2] = "c", since getting reference value mapped 2 , 2 compares equal 1 according function, update key present.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -