Unordered_map::find()插入查找的键

unordered_map::find() inserts the key of the lookup

本文关键字:查找 插入 map find Unordered      更新时间:2023-10-16

unordered_map::find()的一个特性是插入我们自动查找0值的键吗?我把这个写清楚

    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
    }

所以如果我再次查找1,它会在tempMap中以0作为对应值吗?这是unordered_map的特性吗?

不,find只搜索并返回一个迭代器。

也就是说,std::unordered_map(和std::map)都重载operator[],如果需要,插入默认值:

// 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 not insert values.

如果你想插入之前不存在的值,那么你可以使用operator[]而不是find

这样做是因为operator[]返回一个对象的引用。由于不存在空引用这样的东西,本质上唯一的替代方法就是在搜索以前不存在的项时抛出异常。已经有一些容器采用了这种行为,但它显然不是很有用,也没有得到多少普及(我使用过一些这样的容器,发现它很痛苦)。

相关文章: