C++ 的 std::map 容器中插入键值对主要有myMap(std::make_pair(key value)) ,它们的区别你了解吗?
auto it = myMap,find(key) 和 auto value = myMap[key] 都可以用于在 C++ 的 std::map 容器中查找键对应的值,但是如果auto value = myMap[key]的key不存在时会有什么问题呢?
下文就详细介绍它们的区别
C++ 插入主要有:myMap[key] = value
和 myMap(std::make_pair(key,value))
map<int, string> myMap;
myMap.insert(std::make_pair(10,"abc"));
myMap.insert(std::make_pair(10, "abcd"));
cout << myMap[10] << endl;
myMap[11] = "123";
cout << myMap[11] << endl;
myMap[11] = "1234";
cout << myMap[11] << endl;
运行结果
abc
123
1234
可以看到,调用inset方法时,若果该key已经存在,不会更新该key的值,在调用insert函数的时候需要注意。
C++ 的 std::map 容器中查找键对应的值注意是auto it = myMap.find(key)
和 auto value = myMap[key]
map<int, int> myMap1;
myMap1[2] = 2;
cout <<"myMap1 size = "<< myMap1.size() << endl;
int val1 = myMap1[1];
cout << "val1 = " << val1 << "; myMap1 size = " << myMap1.size() << "; myMap1[2] = " << myMap1[2] << endl;
cout << "-------------------------------------" << endl;
map<int, int> myMap2;
myMap2[22] = 22;
cout << "myMap2 size = " << myMap2.size() << endl;
auto it1 = myMap2.find(11);
auto it2 = myMap2.find(22);
if (it1 == myMap2.end())
cout << "myMap2 not find 11" << endl;
if (it2 != myMap2.end())
cout << "key = " << it2->first << "; value = " << it2->second << endl;
cout << "myMap2 size = " << myMap2.size() << endl;
运行结果
myMap1 size = 1
val1 = 0; myMap1 size = 2; myMap1[2] = 2
-------------------------------------
myMap2 size = 1
myMap2 not find 11
key = 22; value = 22
myMap2 size = 1
注意:使用 myMap[key] 时,如果健的类型是自定义类型,需要确保该类型已经实现了合适的默认构造函数,以便在键不存在时能够插入默认值.