c++ - unordered_map::find() 插入查找的键

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

最佳答案

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

关于c++ - unordered_map::find() 插入查找的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7434797/

相关文章:

c++ - 什么是复制省略和返回值优化?

c++ - 为 CString 创建 unordered_map 作为键

c++ - 如果我只想指定一个哈希函数,我应该将什么传递给 unordered_map 的存储桶计数参数?

c++ - 如何避免在插入过程中延迟调整 unordered_map 的大小

c++ - 如何从JNI获取包名到Android?

c++ - C/C++ 别名函数到具有不同参数的其他函数

c++ - std::unordered_map - 未定义模板的隐式实例化?

c++ - C++ STL unordered_map 如何解决冲突?

c++ - 检查 NULL 值 C++ 的引用

C++、海湾合作委员会 : avoid evaluation of useless expressions