c++:新的多维字符串数组

c++: new multi dimensional array of strings

本文关键字:字符串 数组 c++      更新时间:2023-10-16

可能重复:
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];
}

但是,我强烈建议您考虑使用矢量。