简体   繁体   中英

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.

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 .

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}));

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