2

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]>')

Konchog
  • 1,920
  • 19
  • 23
  • @WhozCraig, thanks - that solved the problem I faced, but I would also like to know if it's possible to even use the 'C' style int array construct in an initialisation. – Konchog Jul 27 '21 at 09:20
  • 2
    you should worry about the `int[4]` because you cannot use them as mapped type in an `unordered_map`. See here: https://stackoverflow.com/questions/2582529/how-can-i-use-an-array-as-map-value – 463035818_is_not_an_ai Jul 27 '21 at 11:39

1 Answers1

3

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

Konchog
  • 1,920
  • 19
  • 23
eerorika
  • 232,697
  • 12
  • 197
  • 326