简体   繁体   中英

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 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM