I’d like to find out if two itertors share the same iterable. Like here:
typedef std::list<int> IntList;
IntList l;
IntList j;
// fill the lists
IntList::iterator start = l.begin();
IntList::iterator end = j.end();
std::cout << std::distance(start, end) << std::endl;
This snippet does not work, and for me it’s perfectly clear why it does not: There is no possibility to follow one iterator until it reaches the other and count the steps.
But for me it’s desirable to find out if two iterators point at the same iterable. The usecase is that I have lists and slices while slices have a start and an end pointing somewhere in the list. What I want to find out is if two slices share the same list. A workaround would be to provide my slices with a pointer to the list, of course, and then simply compare these pointers. But it was interesting to know if there is another way.
This question discusses a similar problem.
In short, comparing does not work, because the C++03 standard is not perfectly clear about comparing iterators from different containers, and in C++11 it is explicitly forbidden.
A possible solution that works for standard containers is comparing the addresses of the contained elements.