Elfayer
Elfayer

Reputation: 4561

C++ - How to traverse a list from end to begin?

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?

Upvotes: 4

Views: 5817

Answers (4)

EpiGen
EpiGen

Reputation: 70

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.

Upvotes: 0

stativ
stativ

Reputation: 1490

Use rbegin and rend to get reverse iterators.

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

Upvotes: 21

Sean
Sean

Reputation: 62472

You want a reverse iterator. See rbegin and rend.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227390

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.

Upvotes: 5

Related Questions