Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a value in a map [duplicate]

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));
like image 448
TheOne Avatar asked Feb 11 '26 18:02

TheOne


2 Answers

I 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

like image 66
pxb Avatar answered Feb 15 '26 18:02

pxb


For a map, the former (operator[]) expression will always replace the value part of the key-value pair with the new supplied value. A new key-value pair will be inserted if one doesn't already exist.

In contrast, insert will only insert a new key-value pair if a key-value pair with the supplied key part does not already exist in the map.

like image 41
CB Bailey Avatar answered Feb 15 '26 18:02

CB Bailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!