如何使用<string>初始值设定项列表初始化unordered_map<字符串、unordered_set>成员?
How to initialize unordered_map<string, unordered_set<string>> members using initializer list?
我有这个类
class A {
unordered_map<string, unordered_set<string>> n_;
public:
A(unordered_map<string, unordered_set<string>>& n) : n_{n} {}
};
我希望能够使用该语法
使用构造函数int main() {
A a{{"C", {"A", "B"}}};
return 0;
}
,但现在写的方式,我会遇到错误
error: no matching function for call to `‘A::A(<brace-enclosed initializer list>)’ A a{{"C", {"A", "B"}}};`
如何修复?
您需要为其添加更多{}
。并请注意,临时性不能绑定到lvalue-renfordent to don-const。(它们可以绑定到const或rvalue引用。(例如
class A {
unordered_map<string, unordered_set<string>> n_;
public:
A(const unordered_map<string, unordered_set<string>>& n) : n_{n} {}
//^^^^^
};
int main() {
A a{{{"C", {"A", "B"}}}};
// ^^^ ^^^ elements of unordered_set
// ^^^^^^^^^^ for the unordered_set
// ^^^^^^^^^^^^^^^^^ elements (std::pair) of unordered_map (only one here)
// ^^^^^^^^^^^^^^^^^^^ for the unordered_map
// ^^^^^^^^^^^^^^^^^^^^^ for A
return 0;
}
我想您可能会错过unordered_map
元素(std::pair
(的{}
;以类似的方式,如果您想制作包含两个元素的unordered_map
,则可以将其写为
A b{{{"C", {"A", "B"}}, {"F", {"D", "E"}}}};
live
我希望能够与该语法一起使用构造函数
您可以提供 std :: prinitizer_list 构造函数来完成工作
#include <initializer_list>
class A
{
using MapType = std::unordered_map<std::string, std::unordered_set<std::string>>;
MapType n_;
public:
A(std::initializer_list<MapType::value_type> n) : n_{ n } {}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
};
具有列表初始化不需要额外的{}
的优势。例如带有两个条目的地图:
A a{
{"C", {"A", "B"}},
{"D", {"E", "F"}},
}; // do not require extra braces now!
(请参阅LIVE(
在jarod的(正确(答案的顶部,您缺少一组卷曲括号:
int main() {
A a{{{"C", {"A", "B"}}}};
return 0;
}
来自最内在的:
您需要初始化std::unordered_set
:
{"A", "B"}
在std::pair
{"C", {"A", "B"}}
使用该对初始化std::unordered_map
:
{{"C", {"A", "B"}}}
使用该地图初始化A
的对象:
A a{{{"C", {"A", "B"}}}};
临时性不能绑定到非const(lvalue(参考。
您可能会将构造函数更改为
A(const unordered_map<string, unordered_set<string>>& n) : n_{n} {}
或
A(unordered_map<string, unordered_set<string>>&& n) : n_{std::move(n)} {}
或
A(unordered_map<string, unordered_set<string>> n) : n_{std::move(n)} {}
相关文章:
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- C 字符串比较“祝您好运”&gt;“再见”
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- C 操作员&gt;&gt;与突变器过载
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 是否需要使用 - &gt;运算符在C 中调用成员函数时
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- 错误c++visual studio c2227左侧'->;Init';必须指向类/结构/联合/泛型类型
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- ``这个''不能用this-&gt;指针变量
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是否可以<int>在一行中将向量值分配给 std::unordered<int,std::vector<int>>?
- 是std :: set&lt; std :: future&gt;不可能存在
- 使用shared_ptr<字符串>转换为一个无序集合<字符串>
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾