我在 C++ 映射中有一个基本查询,
map<char,string> mymap;
mymap['a']="an element";
mymap['b']="another element";
mymap['c']=mymap['b'];
cout << "mymap['a'] is " << mymap['a'] << endl;
cout << "mymap['b'] is " << mymap['b'] << endl;
cout << "mymap['c'] is " << mymap['c'] << endl;
cout << "mymap['d'] is " << mymap['d'] << endl;
当我们尝试访问 mymap['d'] 时,我得到了一个默认值,因为运算符使用该键在映射中插入了一个新元素并初始化为它的默认值,即使访问它只是为了检索它的值。下次我使用迭代器时,我可以看到键“d”的空值。有没有办法限制 map 插入默认值。
最佳答案
如果您不想默认插入,您应该使用 map.find
而不是 operator []
。
iterator find ( const key_type& x );
const_iterator find ( const key_type& x ) const;
在容器中搜索以 x 为键的元素,如果找到则返回一个迭代器,否则它返回一个迭代器到 map::end(容器末尾之后的元素)
关于C++ map 添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8806977/