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 keysk1,k2considered equivalent if comparison objectcomp,comp(k1, k2) == false&&comp(k2, k1) == false. 2 keysk1,k2in same container, callingcomp(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
Post a Comment