Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
376 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...