C++ STL <map> 允许重复对吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10732074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
STL <map> allows duplicate pairs?
提问by dead programmer
I have written the following code and was surprised at the output. I heard that <map>
avoids collision of keys, but here it appears to allow insertion of duplicate pairs.
我编写了以下代码并对输出感到惊讶。我听说这样<map>
可以避免键冲突,但在这里它似乎允许插入重复的对。
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<string,char> namemap;
namemap["yogi"]='c';
namemap.insert(pair<string,char>("yogendra",'a'));
namemap.insert(pair<string,char>("yogendra",'b'));
cout<<namemap["yogendra"]<<endl;
return 0;
}
This code outputs a
. You can run it on C++ Shell.
此代码输出a
. 您可以在C++ Shell上运行它。
Does avoiding collision means that we cannot enter multiple pairs with same key?
避免碰撞是否意味着我们不能使用相同的密钥输入多个对?
回答by NPE
The second insert
with the same key is a no-op. It simply returns an iterator pointing to the existing element.
insert
具有相同密钥的第二个是空操作。它只是返回一个指向现有元素的迭代器。
std::map::insert()
has a return value, which you should check.
std::map::insert()
有一个返回值,您应该检查它。
It is of type std::pair<iterator,bool>
. The second element of the pair tells you whether the element has been inserted, or whether there was already an existing entry with the same key.
它的类型为std::pair<iterator,bool>
。该对的第二个元素告诉您该元素是否已被插入,或者是否已经存在具有相同键的条目。
cout << namemap.insert(pair<string,char>("yogendra",'a')).second << endl;
cout << namemap.insert(pair<string,char>("yogendra",'b')).second << endl;
回答by Jay D
STL map does not allow same Keys to be used. You may want to go for multi-map for that.
STL 映射不允许使用相同的密钥。为此,您可能想要使用多地图。
回答by ashutosh
a map will not throw any compile/run time error while inserting value using duplicate key. but while inserting, using the duplicate key it will not insert a new value, it will return the same exiting value only. it will not overwrite. but in the below case it will be overwritten.
使用重复键插入值时,映射不会引发任何编译/运行时错误。但是在插入时,使用重复键不会插入新值,它只会返回相同的现有值。它不会覆盖。但在以下情况下,它将被覆盖。
map<char,int> m1;
m1.insert(pair <char, int> ('a', 40));
m1['a']=50;
cout << "a => " << m1.find('a')->second << '\n';
The result will be 50.
结果将是 50。
below example, it will not overwrite.
下面的例子,它不会覆盖。
map<char,int> m1;
m1.insert(pair <char, int> ('a', 40));
m1.insert(pair <char, int> ('a', 50));
cout << "a => " << m1.find('a')->second << '\n';
Result will be 40.
结果将是 40。
Remember map size 1 here for both the cases.
对于这两种情况,请记住这里的地图大小 1。
cout< "size = " << m1.size() << '\n';
it will be 1 in both cases.
在这两种情况下它都是 1。