[英]Is there any difference between the following commands from std::unordered_map
For inserting a key-value pair into an unordered map, eg, std::unordered_pair<int,int> map1
, can we do it in any of these two ways: 要将键值对插入到无序映射中,例如std::unordered_pair<int,int> map1
,我们可以通过以下两种方式中的任何一种来实现:
map1[2]=5;
map1.insert({2,5});
Is there any difference between using std_unordered_insert
or operator[]
? 使用std_unordered_insert
或operator[]
之间有什么区别吗?
And if I want to find the mapped value for a given key, can I use either of the following: 如果要查找给定键的映射值,可以使用以下两种方法之一:
mappedVal = map1.at(2);
mappedVal = map1[2];
Again, any difference between using std::unordered_map::at
or operator[]
? 同样,使用std::unordered_map::at
或operator[]
之间有什么区别?
map1[2]=5; MAP1 [2] = 5;
If an entry with key 2
exists, set that entry's value to 5
. 如果存在带有键2
的条目,则将该条目的值设置为5
。 Otherwise, create a new entry with key 2
and value 5
. 否则,使用键2
和值5
创建一个新条目。
map1.insert({2,5}); map1.insert({2,5-});
If no entry with key 2
exists, create a new entry with key 2
and value 5
. 如果不存在具有键2
条目,则创建一个具有键2
和值5
的新条目。 Otherwise, do nothing . 否则, 什么都不做 。
mappedVal = map1.at(2); mappingVal = map1.at(2);
If an entry with key 2
exists, assign its value to mappedVal
. 如果存在键为2
的条目, mappedVal
其值分配给mappedVal
。 Otherwise, throw an out_of_range
exception. 否则,抛出out_of_range
异常。
mappedVal = map1[2]; appedVal = map1 [2];
If an entry with key 2
exists, assign its value to mappedVal. 如果存在具有键2
的条目,则将其值分配给mappingVal。 Otherwise, create an entry for 2
using the default value and assign that default value to mappedVal. 否则,使用默认值为2
创建一个条目,并将该默认值分配给mappingVal。
For lookups, I usually use unordered_map::find()
rather than at()
or operator [] ()
(unless I know that there is an entry for the given key). 对于查找,我通常使用unordered_map::find()
而不是at()
或operator [] ()
(除非我知道给定键有一个条目)。
In contrast to operator[]
, at()
will throw a std::out_of_range
exception if the key doesn't exist. 与operator[]
,如果键不存在,则at()
将抛出std::out_of_range
异常。 operator[]
will create the key instead. operator[]
将代替创建密钥。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.