Iterator of list

Hi,

Assuming a list list<double> mylist = {1, 2, 3, ...}
It seems I can not operate directly on iterator of the list, like
for(auto it = mylist.begin(); it != mylist.end()-5; it++)
Here the -5 is not accepted. But it is necessary for me to fix the range from the end of list. How can I do this?

Since std::list uses a bidirectional iterator instead of the random iterator you can't just subtract a number from them. But you can do something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #include <iostream>
#include <iterator>
#include <list>

using namespace std;

int main () {
   list<int> mylist;

   for (int i=0; i<10; i++) mylist.push_back ((i+1)*10);

   auto last = mylist.end();

   for(int i = 0; i < 5; ++i)
      last--;

   for(auto iter = mylist.begin(); iter != last; ++iter)
      cout << *iter << endl;

   return 0;
}


There's also std::prev(mylist.end(), 5), but it doesn't sound like a good use case for list.
Actually it looks perfect for a list. See this link: http://en.cppreference.com/w/cpp/iterator/prev, good find.

This seems to work.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iterator>
#include <list>

using namespace std;

int main () {
   list<int> mylist;

   for (int i=0; i<10; i++) mylist.push_back ((i+1)*10);

   auto last = std::prev(mylist.end(),5);

   for(auto iter = mylist.begin(); iter != last; ++iter)
      cout << *iter << endl;



   return 0;
}
Thanks for the replies. I was writing a template to move iterator backward, like prev. OK, prev it is. :)
Topic archived. No new replies allowed.