alaska
alaska

Reputation: 151

How to iterate a list without the last element

What I want to do is just iterate a std::list except for the last element. What I am trying:

#include <cstdlib>
#include <list>

int main() {
  std::list<int> *list = new std::list<int>(100);
  std::list<int>::iterator it;

  for (it = list->begin(); it != list->end()-1; it++) {
    // some action here...
  }
}

However, this will not work. What is wrong?

Upvotes: 1

Views: 819

Answers (2)

pmr
pmr

Reputation: 59841

As to why this fails:

A list::iterator is a BidirectionalIterator. It cannot be decrement using operator- or increment using operator+. Those operations are reserved for models of RandomAccessIterator. However, you can decrement it using operator--.

std::list<int> x;
// --end(x) would work as well here, but I don't recommend it
auto end = end(x); 
--end;

// or even better
end = std::prev(end(x));

for(auto it = begin(x); it != end; ++it) {

}

Also, please drop the pointers. Your simple example is already leaking memory.

Upvotes: 4

Qaz
Qaz

Reputation: 61970

std::list uses a bidirectional iterator, which doesn't support operator-. Use std::prev instead:

for (it = list->begin(); it != std::prev(list->end()); it++) {
  // some action here...
}

Upvotes: 4

Related Questions