有人能说出使用数组向量的正确方法是什么?
我声明了一个数组(vector<float[4]>)的向量,但error: conversion from 'int' to non-scalar type 'float [4]' requested在尝试时得到resize了.出了什么问题?
我目前正在尝试在 C++20 下构建遗留代码库,我遇到了这样的事情:
\nsize_t someCount; // value comes from somewhere else\n\xe2\x80\xa6\nstd::vector<const char *[2]> keyValues(someCount);\nRun Code Online (Sandbox Code Playgroud)\n我不能轻易地将其更改为类似的内容,std::vector<std:array<const char *, 2>>因为它稍后会传递给我无法控制的某个 API。只要我不启用 C++20,上述令人厌恶的内容就可以在 Clang 和 GCC 甚至 MSVC 中正常编译,但它会在 C++20 中的 MSVC 中中断,正如您在Godbolt 中看到的那样。
我认为这与是否使用上述构造函数的DefaultInsertable要求有关(这实际上是标准强制执行的T唯一要求)。根据 cppreference(请参阅前面的链接),C++17 之前的 STL 实现使用放置 new 来默认构造元素,从 C++20 开始,用于类型。这可能会触发 MSVC 从 C++17 回归到 C++20。std::construct_atDefaultInsertable
该标准规定,DefaultInsertable如果该表达式格式良好,则为类型:
allocator_traits<A>::construct(m, p)\nRun Code Online (Sandbox Code Playgroud)\n所以就我而言,那就是:
\nconst char * dummy[2];\nusing Allocator = std::allocator<const char *[2]>;\nAllocator a;\n// …Run Code Online (Sandbox Code Playgroud)