简体   繁体   中英

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.

Thank you all.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM