Reputation: 532
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.
Thank you all.
Upvotes: 3
Views: 2426
Reputation: 584
Your problem is that the value_type of std::map<std::string,int> is not std::pair<std::string,int>. It is 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. But I'm guessing you probably can, since it's called myMap and not otherGuysMap :) .
Upvotes: 6
Reputation: 119164
container.insert(input.begin(), input.end());
If you want to replace the contents of the map. do container.clear();
first.
Upvotes: 8