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

时间:2011-09-15 17:10:03

标签: c++ unordered-map

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的一个特性吗?

2 个答案:

答案 0 :(得分:8)

不,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]; 

答案 1 :(得分:4)

否 - find不会插入值。

如果您想插入以前不存在的值,则可以使用operator[]代替find

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