Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector - pair uniform initialization

I have a collection defined as -

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

My intention is to use statements like

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

How can I initialize group0 and group1 using initializer list ? 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 on vector-pair initialization but i couldn't see any where second of std::pair is again a collection.

like image 343
essbeev Avatar asked Dec 19 '22 09:12

essbeev


2 Answers

When you write inputs.push_back(std::make_pair("group0", {1, 2, 3, 4})) you're asking make_pair to deduce the types of both its arguments. But the second argument, a braced-init-list, is not an expression, so it has no type. Hence, template argument deduction fails.

The easiest solution is to remove the call to make_pair and use braced-init-lists everywhere.

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

Now, list initialization will enumerate available constructors and call the pair constructor with the outer pair of arguments, and the vector constructor for the inner braced-init-list.

like image 96
Praetorian Avatar answered Dec 24 '22 02:12

Praetorian


While

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

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

inputs.push_back(std::make_pair("group0", Parameters{1, 2, 3, 4}));
like image 45
R Sahu Avatar answered Dec 24 '22 02:12

R Sahu