在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/