1

Given a function such as the following:

template<typename ForwardIterator>
void MyFunc(ForwardIterator first, ForwardIterator last) {
...
}

Given that first and last are in the same data structure, how can I check that first is in fact before last in this data structure?

3 Answers 3

2

Instead of solving this problem, just do what the standard library does: Assert the precondition that last must be reachable from first and be done (note that it may be reachable by identity).

If you don't make that precondition you have to also be given a reference/pointer to the container, or the begin/end of the container in order to do the validation checks.

Sign up to request clarification or add additional context in comments.

1 Comment

@amigo421 Put in your function's documentation that it's the callers responsibility to ensure the iterators are in the correct order.
0

just use std::distance with someContainer.begin() as argument:

auto d1 = std::distance(someContainer.begin() , iterator1);
auto d2 = std::distance(someContainer.begin() , iterator2);

if (d1>d2){..

7 Comments

how can I get the container itself?
@amigo421 You don't need to reference the container. You can just use two iterators with the function.
well, you didn't mention you don't hold the container itself. an iterator is a generalization of a pointer . can you tell if one pointer points to a 'farer' element then another one ? only if the container is contagious. if not , and you don't hold the container , I don't know any method of it
see the description from cppreference.com: The behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first. that is exactly what I want to check - that first < last is ok. but in case if I get function parameters last < first there will undefined behavior, isnot it?
@amigo421 As far as I know it's not possible, given two arbitrary iterators, to tell if they are in the same data structure of not.
|
0

The short answer is "in general, you can't".

The longer answer is: You can increment first over and over again, and if you get to last, then you know that first was "before" last. If you don't get to last, well, maybe you haven't gone far enough - there's no way to tell.

As Mark B says in his answer, the way the standard library does it is to tell the user "It's your responsibility to make sure that last is reachable from first".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.