[英]insert a std::initializer_list into std::map
I have a method like this: 我有这样的方法:
std::map<std::string, int> container;
void myMap(std::initializer_list<std::pair<std::string, int>> input)
{
// insert 'input' into map...
}
I can call that method like this: 我可以像这样调用这个方法:
myMap({
{"foo", 1}
});
How I can convert my custom argument and insert into the map? 我如何转换我的自定义参数并插入到地图中?
I tried: 我试过了:
container = input;
container(input);
But don't work because the parameter of map is only std::initializer_list
and there's no std::pair
there. 但是不行,因为map的参数只是
std::initializer_list
而且那里没有std::pair
。
Thank you all. 谢谢你们。
container.insert(input.begin(), input.end());
If you want to replace the contents of the map. 如果要替换地图的内容。 do
container.clear();
do
container.clear();
first. 第一。
Your problem is that the value_type of std::map<std::string,int> is not std::pair<std::string,int> . 您的问题是std :: map <std :: string,int>的value_type不是std :: pair <std :: string,int> 。 It is std::pair<const std::string, int> .
它是std :: pair <const std :: string,int> 。 Note the const on the key.
注意键上的常量 。 This works fine:
这很好用:
std::map<std::string, int> container;
void myMap(std::initializer_list<std::pair<const std::string, int>> input) {
container = input;
}
If you can't change your function's signature, you have to write a loop or use std::copy to convert each input element into the value_type of the container. 如果无法更改函数的签名,则必须编写循环或使用std :: copy将每个输入元素转换为容器的value_type。 But I'm guessing you probably can, since it's called myMap and not otherGuysMap :) .
但我猜你可能,因为它叫myMap而不是otherGuysMap :)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.