无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量

Cannot initialize a vector of const char*/string array with an initializer-list on declaration

本文关键字:字符 常量 初始化 列表 向量 数组 字符串 声明      更新时间:2023-10-16

最初,我开始尝试初始化一个常量字符*[3]的向量,并在声明时使用发起器列表

vector<const char*[3]> v = { { "a", "b", "c" } };

这给出了错误

matrix must be initialized with a brace-enclosed initializer

我认为这可能是由于常量字符*,尽管看起来很奇怪,并将其更改为字符串

vector<string[3]> v = { { "a", "b", "c" } };

但错误仍然存在。我尝试了几种牙套组合,但无济于事。实际上是否可以使用初始值设定项列表在声明时初始化此结构?

它无法编译,因为std::vector要求其T可复制的。无论它的 RHS 如何,此语句都不会不编译:

vector<const char*[3]> v = { { "a", "b", "c" } }; // Error

就像这也不会编译一样:

std::vector<const char*[3]> v;
const char* charPtrArr[3] { "a", "b", "c" };
v.push_back(charPtrArr); // Error

这只是C 样式数组不可分配的一个特殊情况,直接使用static_assert在代码中演示:

static_assert(std::is_copy_assignable<const char*[3]>()); // Error

或者更一般地说,我猜:

static_assert(std::is_copy_assignable<int[]>()); // Error

如果您真的想要一个大小为 3 的数组std::vector来保存char指针,那么这是无错误的 C++11 方法:

vector<array<const char*, 3>> v = { { "a", "b", "c" }, { "d", "e", "f"} };

问题是 C 样式数组不能通过复制传递或在函数参数中移动。 因此,此代码将不起作用

vector<const char*[3]> v;
const char* item[3] { "a", "b", "c" };
v.push_back(item); // will not compile


https://wandbox.org/permlink/LumvUzPnYWew7uMu 基本上这是同一个问题,但涉及初始化列表。

C++11 为您的问题提供简单的解决方案:

vector<array<const char*, 3>> v { { "a", "b", "c" }, { "d", "e", "f"} };

https://wandbox.org/permlink/IHNoSrH9BWV1IUoQ