无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
Cannot initialize a vector of const char*/string array with an initializer-list on declaration
最初,我开始尝试初始化一个常量字符*[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
相关文章:
- 多字符常量警告
- const_cast<字符 *>(字符* 常量) 不是左值?
- 常量字符数组模板与字符常量* 函数重载
- 如何检查字符常量是否符合ASCII
- 从字符串数组转换为字符* 常量
- 字符常量或字符串常量
- 字符常量数组为空,即使已为其赋值 [C++]
- 如何创建 ' 字符常量
- 如何编写完全可移植的 4 字节字符常量的编译时初始化
- 我得到以下错误:[警告]多字符字符常量
- C++错误:警告:多字符字符常量/a用于用法
- 字符常量和函数名称的 sizeof() 背后的逻辑
- 如何在 C 中将多字符常量转换为整数
- C++ wifstream:不兼容的字符常量*,wchar_t康斯特*类型
- 不允许从"常量无符号字符*常量*"到"常量字符*常量*"static_cast
- 修改字符 *常量字符串
- 为什么字符常量/文字不能为空?
- C++字符 * 常量与字符 *,为什么有时一个有时另一个
- 警告多字符字符常量 [-Wmultichar]
- 开关语句多字符常量