将int数组初始化为类型参数

Initializing an int array as a type argument

本文关键字:类型参数 初始化 数组 int      更新时间:2023-10-16

此代码无法编译:

  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

这应该有效:

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

您可以用一组角括号初始化数组。

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