如何创建新的字符串数组

how to create a new array of strings

本文关键字:字符串 数组 创建 何创建      更新时间:2023-10-16

我不明白这是怎么回事。Im-tring从字符串列表中创建一个字符串数组。我计算列表中的字符串数,然后想创建一个这些字符串的数组。我做了一些测试,得到了这个代码:

string *newOrder;
int numNodes;
numNodes = alphaTree.numNodes();
newOrder = new string [numNodes];
newOrder[0] = "This is";
newOrder[1] = "a test";
newOrder[2] = "To see";
newOrder[3] = "If this";
newOrder[4] = "will work";

结果是,newOrder的行为就像它是一个具有值"This is"的单个字符串数组。我做错了什么?

检查numNodes=alphaTree.numNodes();正在返回所需的大小。

下面是一段正确的代码,为5个字符串进行分配并赋值。

newOrder = new string [5];
newOrder[0] = "This is";
newOrder[1] = "a test";
newOrder[2] = "To see";
newOrder[3] = "If this";
newOrder[4] = "will work";

如果您执行以下语句:

cout << newOrder[2] << endl;

这将打印:查看

using std::string;
using std::vector;
// from an initializer_list
vector<string> newOrder1 = {
    "This is",
    "a test",
    "To see",
    "If this",
    "will work",
};
// as a sequence of appends
// often used in a loop if an iterator is not applicable
vector<string> newOrder2;
newOrder2.push_back("This is");
newOrder2.push_back("a test");
newOrder2.push_back("To see");
newOrder2.push_back("If this");
newOrder2.push_back("will work");
// from an iterator-pair over any standards-compliant container
vector<string> newOrder3(alphaTree.begin(), alphaTree.end());