I have the correct answer but it's just in the wrong order and I'm not sure how to reverse it. I can't add anything before for (int i = 1; i < inputVector.size(); i ) {
#include <iostream>
#include <vector>
using namespace std;
int main() {
int i;
vector<int> inputVector;
int value;
cin >> value;
while (value != -1) {
inputVector.push_back(value);
cin >> value;
}
for (int i = 1; i < inputVector.size(); i ) {
if (inputVector[i] > 0) {
cout << inputVector[i] << " " << endl;
}
}
return 0;
}
CodePudding user response:
Instead of this:
for (int i = 1; i < inputVector.size(); i ) {
if (inputVector[i] > 0) {
cout << inputVector[i] << " " << endl;
}
}
Because your index i
starts at 1
, you are actually skipping the first element at inputVector[0]
. I'm not sure why. But to print the list in reverse, you can adjust the index value by subtracting i
from the index of the last element (size - 1).
for (size_t i = 0; i < inputVector.size(); i ) {
size_t j = inputVector.size() - 1 - i;
if (inputVector[j] > 0) {
cout << inputVector[j] << " " << endl;
}
}
Vector also has a reverse iterator. So you can also do this:
for (auto itor = inputVector.rbegin(); itor != inputVector.rend(); itor ) {
int value = *itor;
if (value > 0) {
cout << value << " " << endl;
}
}
CodePudding user response:
This should be sufficient given your contraints.
for (int i = inputVector.size() - 1; i > 0 ; i )
if (inputVector[i] > 0)
cout << inputVector[i] << " " << endl;