c++ - 如果不存在键,则使用[]运算符访问STL Map元素会添加新元素

标签 c++ stl

在Windows OS中,如果不存在键,则使用[]运算符访问STL Map元素会添加具有默认值的新元素。如何避免呢?

#include <iostream>
#include <map>
#include <string>

int main ()
{
  std::map<char,std::string> mymap;

  mymap['a']="an element";
  mymap['b']="another element";
  mymap['c']=mymap['b'];

  std::cout << "mymap['a'] is " << mymap['a'] << '\n';
  std::cout << "mymap['b'] is " << mymap['b'] << '\n';
  std::cout << "mymap['c'] is " << mymap['c'] << '\n';
  std::cout << "mymap['d'] is " << mymap['d'] << '\n';

  std::cout << "mymap now contains " << mymap.size() << " elements.\n";

  return 0;
}

Output:
mymap['a'] is an element
mymap['b'] is another element
mymap['c'] is another element
mymap['d'] is
mymap now contains 4 elements



访问元素'd'将在映射中添加新元素并初始化为其默认值。如何避免在访问元素时添加新元素?

最佳答案

当您要查找 map 中是否已有对象时,请使用 map 的find成员函数。

#include <iostream>
#include <map>
#include <string>

template <class Map, class Key>
void show(Map const &map, Key key) {
    auto pos = map.find(key);
    if (pos == map.end()) {
        std::cout << "key: '" << key << "' was not found\n";        
    }
    else {
        std::cout << "key: " << key << ", value: " << pos->second << "\n";
    }
}

int main ()
{
    std::map<char, std::string> mymap {
        { 'a', "an element" },
        { 'b', "another element" }
    };

    mymap['c'] = mymap['b'];

    show(mymap, 'a');
    show(mymap, 'b');
    show(mymap, 'c');
    show(mymap, 'e');

    std::cout << "mymap now contains " << mymap.size() << " elements.\n";

    return 0;
}

关于c++ - 如果不存在键,则使用[]运算符访问STL Map元素会添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61813404/

相关文章:

C++ MapViewOfFile 失败

c++ - 显示结构/类错误数组 C++

c++ - 为什么我在使用优先级队列时在 ‘(’ 标记之前缺少模板参数?

c++ - 在类构造函数中初始化线程会导致崩溃吗?

c++ - 在 C++ 中遍历自定义结构列表的小问题

c++ - 如何开启STL向后兼容?

c++ - 在 LINUX 中的迭代器之前预期为 ';' (c++)

c++ - 具体来说,标准在哪里规定修改 const 对象是未定义的行为?

c++ - 如何区分终止程序的不同方式?

c++ - 变量或字段 'psort' 声明无效