Reputation: 7344
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.
Upvotes: 1
Views: 146
Reputation: 5702
C++ iterators are designed to be very lightweight, so they generally don't contain a pointer back to their container. Instead, we either design algorithms to take ranges of iterators that the caller guarantees point into the same container, like std::unique
or boost::sort
, or we pass both the container and its iterators together, like std::vector::erase
, again relying on the caller to keep track of which iterators point into which containers.
Upvotes: 1
Reputation: 76838
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.
Upvotes: 1