Search code examples
c++c++11unordered-mapinitializer-listunordered-set

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


I have this class

class A {
    unordered_map<string, unordered_set<string>> n_;
  public:
    A(unordered_map<string, unordered_set<string>>& n) : n_{n} {}
};

And I want to be able to use the constructor with that syntax

int main() {
    A a{{"C", {"A", "B"}}};
    return 0;
}

But in the way it's written now, I'm getting error

error: no matching function for call to `‘A::A(<brace-enclosed initializer list>)’ A a{{"C", {"A", "B"}}};`

How can it be fixed?


Solution

  • You need to add one more {} for it. And note that temporary can't be bound to lvalue-reference to non-const. (They could be bound to lvalue-references to const or rvalue-references.) e.g.

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

    I guess you might miss the {} for the elements (std::pair) of the unordered_map; in a similar fashion, if you want to make the unordered_map containing two elements, you can write it as

    A b{{{"C", {"A", "B"}}, {"F", {"D", "E"}}}};
    

    LIVE