What element number iterator is pointing to?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <list>

using namespace std;

int main()
{
     int myints[] = {75,23,65,42,13};
     list<int> mylist (myints,myints+5);

     for (list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it){
        cout << "Element " << it << " is equal to " << *it << endl; //error here
     }

     return 0;
}


I would expect output to be:
Element 0 is equal to 75
Element 1 is equal to 23
Element 2 is equal to 65
Element 3 is equal to 42
Element 4 is equal to 13

Why it dont work like this ? Is there any other way to find out what iterator is pointing to ?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <iterator>
#include <list>

int main()
{
     int myints[] = {75,23,65,42,13};
     std::list<int> mylist (myints,myints+5);

     for (std::list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it){
          std::cout << "Element " << std::distance(it,mylist.begin()) << " is equal to " << *it << std::endl;
     }

     return 0;
}

Try this. Iterators are basically pointers, so if you want to get the element number from an iterator use std::distance to find out how far along it is from the start of the container. Alternatively, use std::vector which is much more suited to this sort of thing, and replace std::distance with it-myvector.begin().
There is no ostream operator<< that takes any iterator type.

An iterator is a light-weight object, but nevertheless an object with unique type and there are endless amount of different iterator types.

In order to know the "element number" most iterators would have to store it in them or compute on the fly from the container's start. Either way, that would increase the iterator's size and add maintenance hurdle.

Besides, what should this print:
1
2
std::list<Foo>::iterator it;
std::cout << it << '\n';



You can explicitly use http://www.cplusplus.com/reference/iterator/distance/
Thankyou shadowmouse and keskiverto now code works fine!
Topic archived. No new replies allowed.