我不明白这种方式的运作方式。我想从字符串列表中创建一个字符串数组。我计算列表中的字符串数,然后想要创建这些字符串的数组。我正在做一些测试并想出了这段代码:
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就像是一个单独的字符串数组,其vaule为“This is”。 我做错了什么?
答案 0 :(得分:1)
检查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;
这将打印:要查看
答案 1 :(得分:0)
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());