0
#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?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Saunved Mutalik
  • 381
  • 2
  • 19

1 Answers1

1

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)
GoodDeeds
  • 7,956
  • 5
  • 34
  • 61
  • 4
    Decrementing iterator equal to `begin()` is UB. Reverse iterators use special care to avoid this. You have to use `break` in the loop, use reverse iterators or handle `.begin()` out of the loop. – Revolver_Ocelot Aug 13 '16 at 18:54
  • 1
    @Revolver_Ocelot Can you please explain how it invokes undefined behavior? – Shubham Aug 13 '16 at 19:38
  • @Shubham Creatin iterator which are not pointing inside the container or are one-past-the-end iteratirs is illegal for all standard iterators. At the last iteration you are decrementing iterator equal to `begin()`, which takes you outside container. – Revolver_Ocelot Aug 13 '16 at 20:01
  • @Revolver_Ocelot True, but after decrementing the iterator in the last cycle, we are not using it or dereferencing it. So how does this affect the program? – Shubham Aug 13 '16 at 20:13
  • @Shubham mere act of creating iterator outside of container is UB. It does not matter if you do not dereference it. For complex containers, iterator creation might access container. For arrays/vectors and segmented memory, you migh find that `--begin > begin` – Revolver_Ocelot Aug 13 '16 at 20:26