unordered_map::find() inserts the key of the lookup
Is it a feature of unordered_map::find() to insert the key that we lookup with 0 value automatically? Let me make this clear
unordered_map<int, int> tempMap;
//some code
if(tempMap.find(1) == tempMap.end()){
//do开发者_Go百科 something but not insert the 1 with a corresponding value into the tempMap
}
so if I lookup 1 again, will it be there in the tempMap having 0 as corresponding value. Is that a feature of unordered_map?
No, find
only searches and returns an iterator.
That said, std::unordered_map
(and std::map
) both overload operator[]
which will insert a default if needed:
// if element with a key value one exists, return that. otherwise, insert
// a default initialized element (zero in this case), and return that
auto& val = tempMap[1];
No -- find
does not insert values.
If you want to insert the value if it was not previously present, then you can use operator[]
instead of find
.
This is done because operator[]
returns a reference to an object. Since there's no such thing as a null reference, essentially the only alternative would be to have it throw an exception when searching for an item that wasn't previously present. There have been some containers that adopted that behavior, but it wasn't apparently very useful and never gained much popularity (I used some containers like that and found it a pain).
精彩评论