initialise failing for const unordered_map < std::string, int[4] > (clang 12 / c++20)

Viewed 131

I guess I am doing something wrong with the initialisation here, and would like to know what, and why! (I'm not worried about using int[4] here - it's a const map which will be script-generated).

#include <unordered_map>
#include <string>
 
int main() {
    const std::unordered_map<std::string, int[4]>  m { 
        { "alo", {2,2,1,2} },{ "bok", {1,4,0,7} }
    };
}

compiling with:

g++ -std=c++20 foo.cpp

foo.cpp:5:52: error: no matching constructor for initialization of 'const std::unordered_map<std::string, int [4]>' (aka 'const unordered_map<basic_string, int [4]>')

1 Answers

You may not use arrays as element of a map, nor as element of any other standard container.

This is because Arrays are not first class constructs in C++. They are not Copy Constructible nor Assignable which are requirements for values of std::map.

You can however have an array as member of a class and such wrapper class may be used as element of a container. The standard library also provides a template for such wrapper class: std::array

Related