2

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

4

2 回答 2

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]; 
于 2011-09-15T17:30:46.257 回答
4

否 -find不插入值。

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

这样做是因为operator[]返回对对象的引用。由于没有空引用之类的东西,基本上唯一的选择是在搜索以前不存在的项目时让它抛出异常。已经有一些容器采用了这种行为,但它显然不是很有用,也从未获得过广泛的欢迎(我使用了一些这样的容器,发现它很痛苦)。

于 2011-09-15T17:42:55.917 回答