Home > Blockchain >  Output numbers in reverse (C ) w/ vectors
Output numbers in reverse (C ) w/ vectors

Time:04-12

I'm stuck for the first time on a lab for this class. Please help!

The prompt is: Write a program that reads a list of integers, and outputs those integers in reverse. The input begins with an integer indicating the number of integers that follow. For coding simplicity, follow each output integer by a comma, including the last one.
Ex: If the input is:
5 2 4 6 8 10
the output is:
10,8,6,4,2,

2 questions: (1) Why does the vector not take user input unless the const int is included? (2) Why does the code not work in general? It seems to properly output, but with an error, and does not include the end line?

#include <iostream>
#include <vector>   
using namespace std;

int main() {
   const int MAX_ELEMENTS = 20;
   vector<int> userInts(MAX_ELEMENTS);
   unsigned int i;
   int numInts;
   
   cin >> numInts;
   
   for (i = 0; i < numInts;   i) {
      cin >> userInts.at(i);
   }
   
   for (i = (numInts - 1); i >= 0; --i) {
      cout << userInts.at(i) << ",";
   }

   cout << endl;

   return 0;
}

CodePudding user response:

Firstly, you need to specify the size because you are not using the vector's push_back functionality. Since you are only using at, you must specify the size ahead of time. Now, there's a few ways to do this.

Example 1:

cin >> numInts;
vector<int> userInts(numInts); // set the size AFTER the user specifies it
   
for (i = 0; i < numInts;   i) {
   cin >> userInts.at(i);
}

Alternatively, using push_back you can do:

vector<int> userInts; // set the size AFTER the user specifies it
   
for (i = 0; i < numInts;   i) {
   int t;
   cin >> t;
   userInts.push_back(t);
}

As for looping backwards, i >= 0 will always be true for unsigned numbers. Instead, you can use iterators.

for ( auto itr = userInts.rbegin(); itr != userInts.rend();   itr ) {
    cout << *itr;
}

If you need to use indexes for the reverse loop, you can do:

for ( i = numInts - 1; i != ~0; --i ) { // ~0 means "not 0", and is the maximum value, I believe this requires c  17 or 20 though
    cout << userInts.at(i);
}

CodePudding user response:

with unsigned int i; the condition i >= 0 is always true. Eventually you will access an out-of-range element, which will throw std::out_of_range.

CodePudding user response:

To answer your other question

  std::vector userInts;

create a vector with no entries

 userInts.at(i)

tries to access the (non existnat) ith entry.

You have 2 choices

  • create vector with a lot of empty etries
  • ask the vector to dynamically grow

The first one is what you did

 const int MAX_ELEMENTS = 20;
 vector<int> userInts(MAX_ELEMENTS);

Or you can do

 userInts.push_back(x);

this will make sure there is enough space in the vector and add the new element to the end.

  • Related