What is the difference between the index overloaded operator and the insert method call for std::map?
ie:
some_map["x"] = 500;
vs.
some_map.insert(pair<std::string, int>("x", 500));
See Question&Answers more detail:osWhat is the difference between the index overloaded operator and the insert method call for std::map?
ie:
some_map["x"] = 500;
vs.
some_map.insert(pair<std::string, int>("x", 500));
See Question&Answers more detail:osI believe insert() will not overwrite an existing value, and the result of the operation can be checked by testing the bool value in the iterator/pair value returned
The assignment to the subscript operator [] just overwrites whatever's there (inserting an entry if there isn't one there already)
Either of the insert and [] operators can cause issues if you're not expecting that behaviour and don't accommodate for it.
Eg with insert:
std::map< int, std::string* > intMap;
std::string* s1 = new std::string;
std::string* s2 = new std::string;
intMap.insert( std::make_pair( 100, s1 ) ); // inserted
intMap.insert( std::make_pair( 100, s2 ) ); // fails, s2 not in map, could leak if not tidied up
and with [] operator:
std::map< int, std::string* > intMap;
std::string* s1 = new std::string;
std::string* s2 = new std::string;
intMap[ 100 ] = s1; // inserted
intMap[ 100 ] = s2; // inserted, s1 now dropped from map, could leak if not tidied up
I think those are correct, but haven't compiled them, so may have syntax errors