这是我的代码:
map <pair<int,int> ,string> m;
m.insert(make_pair(1,2),"imtiaz");//making key value pair
m.insert(make_pair(8,3),"moin");
m.insert(make_pair(1,2),"izm");
cout<<m[make_pari(1,2)]<<endl; //print value for key 1,2
output:
imtiaz
我们知道如果我们在 map 中为现有键插入一个值,它将更新该值。这里对于同一个键 (1,2) 我插入两个值“imtiaz”和“izm”。所以,最新的值“izm”应该打印在这里.这里有什么问题?
最佳答案
这是 insert
的预期行为不覆盖 map 中的现有条目。
使用 insert_or_assign
(C++17) 对于您期望的行为。在较旧的 C++ 版本中,将赋值与 operator[]
一起使用更新(或插入)一个元素。
那么为什么是 insert_or_assign
介绍?从上面的链接:
insert_or_assign returns more information than operator[] and does not require default-constructibility of the mapped type.
关于c++ - 为什么 c++ 映射值不会为相同的键更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59899302/