Question

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.

Was it helpful?

Solution

container.insert(input.begin(), input.end());

If you want to replace the contents of the map. do container.clear(); first.

OTHER TIPS

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 :) .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top