Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Reversing Order of Values in a Vector without the use of a reiterator

Read integers from input and store each integer into a vector until 0 is read. Do not store 0 into the vector. Then, output all values in the vector in reverse order, each on a new line.

This is the current code I used and for some reason it only outputs 2 or 3 values instead of all of them. Is there something I did wrong?

int main() {
    unsigned int i;
    int inputNum;
    vector<int> vectorNum;

    cin >> inputNum;

    while (inputNum != 0) {
        vectorNum.push_back(inputNum);
        cin >> inputNum;
    }

    for (i = 0; i < vectorNum.size(); ++i) {
        cout << vectorNum.back() << endl;
        vectorNum.pop_back();
    }

    return 0;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With this:

for (i = 0; i < vectorNum.size(); ++i) {
  cout << vectorNum.back() << endl;     
  vectorNum.pop_back();
}

the issue is that you are increasing i in the for loop, but decreasing the number of entries in the vector with pop_back(). Both things occurring will result in less items processed.

Instead of a for loop, use while() and the empty() member function:

while (!vectorNum.empty())
{
   cout << vectorNum.back() << endl;    
   vectorNum.pop_back();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading