【问题标题】:initialise failing for const unordered_map < std::string, int[4] > (clang 12 / c++20)const unordered_map < std::string, int[4] > (clang 12 / c++20) 的初始化失败
【发布时间】:2021-10-03 02:43:56
【问题描述】:

我想我在这里的初始化做错了,想知道是什么,为什么! (我不担心在这里使用 int[4] - 这是一个将由脚本生成的 const 映射)。

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

编译:

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

foo.cpp:5:52: 错误:没有匹配的构造函数用于初始化 'const std::unordered_map<:string int>'(又名 'const unordered_map ')

【问题讨论】:

  • @WhozCraig,谢谢 - 这解决了我面临的问题,但我也想知道是否可以在初始化中使用“C”风格的 int 数组构造。
  • 您应该担心int[4],因为您不能将它们用作unordered_map 中的映射类型。见这里:stackoverflow.com/questions/2582529/…

标签: c++ clang unordered-map


【解决方案1】:

您不能将数组用作地图的元素,也不能用作任何其他标准容器的元素。

这是因为数组不是 C++ 中的第一类构造。它们不是 Copy Constructible 也不是 Assignable,这是 std::map 值的要求。

但是,您可以将数组作为类的成员,并且这样的包装类可以用作容器的元素。标准库还为此类包装类提供了模板:std::array

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多