如何使用<string>初始值设定项列表初始化unordered_map<字符串、unordered_set>成员?

How to initialize unordered_map<string, unordered_set<string>> members using initializer list?

本文关键字:unordered gt lt map 字符串 初始化 set 成员 string 何使用 列表      更新时间:2023-10-16

我有这个类

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