[英]Why a vector constructor takes only last value of the parameter when using in unordered_map emplace?
I'm trying to implement unordered_map> with using unordered_map::emplace 我正在尝试使用unordered_map :: emplace实现unordered_map>
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main ()
{
unordered_map<char,vector<int>> amap;
amap.emplace('k',(2,9));
for(auto i : amap['k']){
cout << i;
}
}
I expected output as "99" because I constructed the vector with (2,9). 我期望输出为“ 99”,因为我用(2,9)构造了向量。 but actual outcome was "000000000" which the emplace constructed vector as (9), 0 being default and 9 as number of ints.
但是实际结果是“ 000000000”,其中Emplace构造矢量为(9),0为默认值,9为整数数。 I played around little more with other parameter values and realized the emplace only took last value in vector parameter.
我对其他参数值进行了更多操作,并意识到Emplace仅采用了矢量参数中的最后一个值。 Why is it?
为什么?
I can still accomplish the goal by doing 我仍然可以通过完成目标来实现
vector<int> v(2,9);
amap.emplace('k',v);
but just wondering why, and save one line of code. 但只是想知道为什么,并保存一行代码。
amap.emplace('k',(2,9));
Here (2,9)
is just comma separated values. 这里
(2,9)
只是逗号分隔的值。 Where everything before ,
is ignored. 这里的一切之前
,
将被忽略。 So it is like 所以就像
amap.emplace('k', (9));
gcc
even throws a warning gcc
甚至会发出警告
warning: expression result unused [-Wunused-value]
警告:表达式结果未使用[-Wunused-value]
You can use the below 您可以使用以下
amap.emplace('k', vector<int>(2,9));
The expression (2,9)
is using the built-in comma operator , and the result of that is 9
. 表达式
(2,9)
使用内置的逗号运算符 ,其结果为9
。
You need to provide a proper std::vector
object, as in std::vector<int>(2, 9)
instead. 您需要提供一个正确的
std::vector
对象,如std::vector<int>(2, 9)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.