Reputation: 55
I don't understand the way this is working. Im tring to create an array of strings from a list of strings. I count the number of strings in the list and then want to create an array of these strings. I was doing some testing and came up with this code:
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";
The results are that newOrder acts like it is a single string array having the vaule "This is". What am I doing wrong?
Upvotes: 0
Views: 104
Reputation: 16036
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());
Upvotes: 0
Reputation: 7118
Check if numNodes = alphaTree.numNodes(); is returning desired size.
The following is a correct piece of code, allocates for 5 strings, and assigns.
newOrder = new string [5];
newOrder[0] = "This is";
newOrder[1] = "a test";
newOrder[2] = "To see";
newOrder[3] = "If this";
newOrder[4] = "will work";
If you execute the following statement:
cout << newOrder[2] << endl;
This will print: To see
Upvotes: 1