Uniform initialization of vector pairs

I have a collection defined as

using Parameters = std::vector<int>; using Group = std::pair<std::string, Parameters>; std::vector<Group> inputs; 

I intend to use expressions such as

 inputs.push_back(group0 /*What goes in here ?*/); inputs.push_back(group1 /*What goes in here ?*/); 

How to initialize group0 and group1 using a list of initializers? This code like this doesn't seem to work

 inputs.push_back(std::make_pair("group0", {1, 2, 3, 4})); 

EDIT: There are already existing questions about initializing vector pairs, but I could not see where second of std::pair again a collection.

+5
source share
2 answers

When you write inputs.push_back(std::make_pair("group0", {1, 2, 3, 4})) , you ask make_pair to infer the types of both of its arguments. But the second argument, the init-list bit, is not an expression, so it has no type. Therefore, the output of the template argument is not performed.

The simplest solution is to remove the make_pair call and use the list-bit in all versions.

 inputs.push_back({"group0", {1, 2, 3, 4}}); 

Now the list initialization lists the available constructors and calls the pair constructor with an external pair of arguments, and the vector constructor for the internal copied initialization list.

+10
source

While

 inputs.push_back({"group0", {1, 2, 3, 4}}); 

works correctly for what you intend to do, I think it’s more expressive to use:

 inputs.push_back(std::make_pair("group0", Parameters{1, 2, 3, 4})); 
+1
source

Source: https://habr.com/ru/post/1265270/


All Articles