Saunved Mutalik Saunved Mutalik - 3 months ago 10
C++ Question

Push_back method works differently in this code. Why?

#include<bits/stdc++.h>
#define MAX 20
using namespace std;
int main()
{
//Creating a vector
vector <int> v;
std::vector<int>::iterator vIterator;
int i;

for(i=1;i<MAX;i++)
{
v.push_back(i);
}

cout<<"Numbers:"<<endl;
for(vIterator = v.end();vIterator>v.begin();vIterator--)
{

cout<<*vIterator<<endl;
}

int el_count = v.size();
cout<<"Size="<<el_count;

return 0;
}


Here's the output of the code:

Numbers:
0
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
Size=19

Why am I getting this "0" at the start?
And why does my list begin with a 2?

Answer

This is because the range of indices of a vector is from v.begin() to v.end()-1. You are instead using it from v.begin()+1 to v.end().

The statement in the loop should be,

for(vIterator = v.end()-1; vIterator>=v.begin(); --vIterator)

Accessing v.end() would be undefined behaviour, here giving a 0, and clearly you are skipping the first element.

Edit: (Thanks to @Revolver_Ocelot)

As can be seen from the comments, in the last iteration, when vIterator=v.begin(), and then vIterator-- is called, the location pointed by the iterator will result in undefined behaviour. This is because vIterator>=v.begin() may or may not be true when vIterator is decremented below v.begin(). An alternative could be,

for(vIterator = v.end()-1; vIterator>v.begin(); --vIterator)
{
    cout<<*vIterator<<endl;
}
cout<<*vIterator<<endl;

Another way would be using reverse iterators,

std::vector<int>::reverse_iterator vIterator;
for(vIterator = v.rbegin(); vIterator!=v.rend(); ++vIterator)