初始化一个int数组作为类型参数

时间:2019-03-13 09:30:35

标签: c++ arrays

此代码无法编译:

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

作为类型参数传递时初始化此int数组的正确方法是什么?

我尝试过:int[]array<int,4>,但它们都给出了错误:

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

2 个答案:

答案 0 :(得分:5)

这应该有效:

#include <array>

std::unordered_map<char, std::array<int, 4>> inv = {{ 'a', {{0, 0, 1, 0}} }};

答案 1 :(得分:2)

您可以使用一组尖括号来初始化数组。

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

示例:https://rextester.com/FOVMLC70132