3

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?

4

4 回答 4

20

Use rbegin and rend to get reverse iterators.

for (std::list<...>::reverse_iterator it=list.rbegin(); it!=list.rend(); ++it)
于 2013-03-18T13:55:20.057 回答
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.

于 2013-03-18T13:56:06.623 回答
1

You want a reverse iterator. See rbegin and rend.

于 2013-03-18T13:56:24.233 回答
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.

于 2014-03-17T20:52:21.380 回答