Vector Lists | Sololearn: Learn to code for FREE!

0

# Vector Lists

HY ALL, I JUST COMPILED THIS CODE BUT IT WONT GIVE ME THE EXPECTED OUTPUT. Please help to debug. #include <iostream> #include <vector> #include <string> using namespace std; int main() { vector<string> stringList; vector<string>::iterator stringListIterator; for(stringListIterator = stringList.begin(); stringListIterator != stringList.end(); ++stringListIterator) { cout << "Enter a string" ; string stringName; cin >> stringName; stringList.push_back(stringName); if(stringList.size() == 10) { break; } } for(stringListIterator = stringList.begin(); stringListIterator != stringList.end(); ++stringListIterator) { cout << *stringListIterator; cout << endl; } return 0; }

10/8/2019 8:14:49 PM

Dianah Delisile

8 Answers

New Answer

+2

Yes the vector size is '0' == empty, so there's nothing to iterate over in the input section. unsigned int mynum = 12; // or put 12 or what ever you like in the for loop, up to you. for(unsigned int x = 0; x < mynum; x++) // use this. { cout << "Enter a string" ; string stringName; cin >> stringName; stringList.push_back(stringName); if(stringList.size() == 10) { break; } }

0

Your stringList is empty, there's nothing to iterate over.

0

I assumed that the vector was initialized to vector.size = 0 at declaration, and returns a pointer to the base address. The first for loop is my attempt at initializing the vector values to 10 using the if statement in the loop.

0

https://code.sololearn.com/ck3PJ8lO0ujb/?ref=app This displays the size of the vector after declaration, all other statements are put within comments.

0

Hy, I managed to revise my code. initial Code for(stringListIterator = stringList.begin(); stringListIterator = stringList.end(); ++stringListIterator) //stringListIterator = stringList.begin() == stringListIterator != stringList.end(), therefore doesn't enter the for-block New Code using while loop https://code.sololearn.com/cvvN1YSnsDMO

0

ah but what is someone enters something other than Y/y/N/n?

0

In that case an assert macro should do the trick

0

Although I class myself as a beginner...I am aware that a assert macros are used for debugging and are normally disabled/'switch off' in the production/final version of progs.