4

I would like to display my list from the end to the beginning. Like:

for (std::list<T>::const_iterator it = list.end(); it != list.begin(); --it)

The problem is that it doesn't enter in when it is in the first element (list.begin()). How can I do this?

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Elfayer
  • 4,411
  • 9
  • 46
  • 76

4 Answers4

21

Use rbegin and rend to get reverse iterators.

for (std::list<...>::reverse_iterator it=list.rbegin(); it!=list.rend(); ++it)
stativ
  • 1,452
  • 12
  • 23
  • 3
    and as a bonus, you can use `auto`: `for( auto it=list.rend(); it!=list.rbegn(); ++it ) {...}` – xtofl Mar 18 '13 at 13:57
5

Use reverse iterators:

for (std::list<...>::const_reverse_iterator it = l.rbegin(); it != l.rend(); ++it)

C++11

for (auto it = l.crbegin(); it != l.crend(); ++it)

and please don't name your std::list<T> instance list.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 1
    I believe a reverse iterator should still start with `rbegin` (the last element)... and go to `rend` (the first element), right? Your answer has it backwards. – abelenky Mar 18 '13 at 13:58
  • 1
    @abelenky Yes that is completely correct. I had a bad cut and paste fail from OP's code. – juanchopanza Mar 18 '13 at 13:59
1

You want a reverse iterator. See rbegin and rend.

Sean
  • 60,939
  • 11
  • 97
  • 136
0

Addition: Because in it = list.end(); it gets => pointer [some block of memory] which is understood as "end" (or point where to stop, right or left boundary). So output its content (cout<<*it) you will see memory[block] address. If you declare and use as this:

std::list<...>::const_iterator it = list.begin();
  std::list<...>::const_iterator iTail = list.end();
  while(it!=iTail)
  {
      //do smthing
      ++it;
  }

either loop will be skipped or you will get some garbage from heap. Its case of const_iterator (didn't read documentation but obviously for "write" protection). In case of iterator std::list<...>::iterator only .end() points to the last[element] => [end]. In cases:

std::list<...>::const_reverse_iterator and std::list<...>::reverse_iterator

iterator shifted automatically to the first elem, depending on start => end or end =>start you are going to run through list.

EpiGen
  • 70
  • 6