矢量 - 对统一初始化

ess*_*eev 4 c++ stdvector c++11 std-pair list-initialization

我有一个集合定义为 -

using Parameters = std::vector<int>;
using Group = std::pair<std::string, Parameters>;
std::vector<Group> inputs;
Run Code Online (Sandbox Code Playgroud)

我的意图是使用像这样的陈述

inputs.push_back(group0 /*What goes in here ?*/);
inputs.push_back(group1 /*What goes in here ?*/);
Run Code Online (Sandbox Code Playgroud)

如何初始化group0group1使用初始化列表?像这样的代码似乎不起作用

inputs.push_back(std::make_pair("group0", {1, 2, 3, 4}));
Run Code Online (Sandbox Code Playgroud)

编辑:有矢量,对初始化已经存在的问题,但我看不出任何地方secondstd::pair又是一个集合.

Pra*_*ian 10

当你写的时候,inputs.push_back(std::make_pair("group0", {1, 2, 3, 4}))你要求make_pair推断出它的两个论点的类型.但第二个参数,一个braced-init-list,不是一个表达式,所以它没有类型.因此,模板参数推断失败.

最简单的解决方案是删除对所有地方的调用make_pair并使用braced-init-lists.

inputs.push_back({"group0", {1, 2, 3, 4}});
Run Code Online (Sandbox Code Playgroud)

现在,列表初始化将枚举可用的构造函数,pair使用外部参数对和vector内部braced-init-list的构造函数调用构造函数.