c++:新的多维字符串数组
c++: new multi dimensional array of strings
可能重复:
C++多维阵列
我正在尝试创建一个类,该类基于对象构造函数参数之一创建任意大小的字符串数组。
这里是我目前正在尝试的对象构造函数的代码:
commandSpec::commandSpec(int numberOfCommands)
{
std::string * commands = new std::string[3][numberOfCommands];
}
我收到一个错误:"numberOfCommands不能出现在常量表达式中",有人能告诉我在执行之前我不知道其大小的对象中指定数组的正确方法吗。
谢谢,j
这可能应该实现为一个结构和一个向量,如下所示:
struct command {
std::string first;
std::string second;
std::string third;
};
commandSpec::commandSpec(int numberOfCommands)
{
std::vector<command> commands(numberOfCommands);
}
当然,您应该为command
的成员选择合适的名称。
只有在堆上分配时才允许使用可变长度数组。
您需要分两步分配数组——首先分配长度为3
的数组(来自指针),然后循环遍历3个元素,并为每个元素分配新的字符串。
我建议您改用std::vector
。
我会使用std::矢量,让生活更轻松:
commandSpec::commandSpec(int numberOfCommands)
{
std::vector<std::vector<std::string>> mystrings(numberOfCommands);
}
反转维度的顺序。。。
commandSpec::commandSpec(int numberOfCommands)
{
std::string (*commands)[3] = new std::string[numberOfCommands][3];
}
但是,我强烈建议您考虑使用矢量。
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组