Suppose I have a container with three iterators, it1, it2 and it3. Now I am using it1 and it2 to define a range, e.g. to pass to some std algorithm.
How do I find out, whether it3 lies within the range defined by it1 and it2?
I am aware of the brute force method of advancing a temporary iterator from it1 to it2 and checking against it3 at each step. Is there a quicker way?
The preferred solution would be in standard C++, without libraries such as boost.
edit: It is not given apriori that ìt3 acts on the same instance of a given container, for it1 and it2 that is always the case. So an additional qustion is: Is there a way to find out that two iterators belong to the same instance of a container?
Random access iterators are comparable. Just do
it1 < it3 && it2 > it3– if they belong to the same collection.You get random access iterators on collections that support O(1) indexing, such as
vector,deque, andarray.edit: Checking if an interator belongs to a given collection is not obviously feasible, and this should be a whole different question. See this question for more details. (tl;dr: you can’t.)