0

This code fails to compile:

  unordered_map<char, int[4]> inv = {
    { 'a', {{0,0,1,0}} } 
  }

What's the proper way to initialize this int array when passed as a type argument?

I've tried: int[], array<int,4> but they all give the error:

no instance of constructor "std::unordered_map<_Kty, _Ty, _Hasher,
_Keyeq, _Alloc>::unordered_map [with _Kty=char, _Ty=std::pair<Cell *, int []>, _Hasher=std::hash<char>, _Keyeq=std::equal_to<char>,
 _Alloc=std::allocator<std::pair<const char, std::pair<Cell *, int []>>>]" matches the argument list
5
  • 2
    This code should complain that unordered_map is undefined. Post actual code that fails to compile. Commented Mar 13, 2019 at 9:38
  • 1
    @ÖöTiib: ??? Should user provide the needed header files? Is this now common in SO? Commented Mar 13, 2019 at 9:39
  • 1
    @Klaus The user should provide a minimal reproducible example. Commented Mar 13, 2019 at 9:40
  • @Klaus he is hiding a using std; so what unordered_map is he using? He may have implemented his own :) Commented Mar 13, 2019 at 9:41
  • @Klaus considering OP's comments to accepted answer it seems that defect was in a #include being missing. Commented Mar 13, 2019 at 9:46

2 Answers 2

5

This should work:

#include <array>

std::unordered_map<char, std::array<int, 4>> inv = {{ 'a', {{0, 0, 1, 0}} }};
Sign up to request clarification or add additional context in comments.

4 Comments

Which compiler are you using? Works for me with clang 7 and gcc 8.
Actually include <array> fixed it, threw me off because the error was the same as when I used int[]
@lubgr can you explain why int[4] doesn't work but std::array<int, 4> does? Just curious :)
@LarsNielsen std::unordered_map<char, int[4]> myMap; will compile, but any insertion will fail to compile, because you can't assign to an existing int[4] array, e.g. myMap['a'] = {1, 2, 3, 4}; gives you something like "int[4] is not assignable". Same as int test[4] = {1, 2, 3, 4}; (which works) and then test = {5, 6, 7, 8}.
2

You can initialize the array with one set of angle brackets.

int main()
{
    std::unordered_map<char,std::array<int,4>> inv = {{ 'a', {1,2,3,4} }};

    for (auto &&i : inv)
        std::cout<< i.first << "->" <<i.second[0] <<std::endl;
}

Example: https://rextester.com/FOVMLC70132

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.