Johnas
Johnas

Reputation: 1283

Compare iterators, C++

Is it possible to compare two iterators? A comparision using std::min

void change ( typename TList <Item *>::Type ::iterator it_begin, typename TList <Item*>::Type ::iterator it_end )
{
   ....
this->items.resize ( index );
   std::sort ( it_begin, std::min (it_end, it_begin += index - 1); //Compare two iterators, exception
....
}

throws the following exception:

Assertion failed: Vector iterators  incompatible... 

Is there any other way of the comparision?

Upvotes: 17

Views: 55440

Answers (4)

user3731622
user3731622

Reputation: 5095

In the book C++ Primer 5th Ed. on p.111 section 3.4.2 Iterator Arithmetic says,

we can use == and != to compare to valid iterators into any of the library containers.

The section also tells us that iterators for string and vector support relational operators (aka iterator arithmetic) which include >, >=, <, <=.

Upvotes: 6

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361302

Yes. But I doubt if you can do that with std::min.

You can use std::distance function to calculate the distance between two iterators. And then you can use the distance to determine which iterator is the smaller one. Once you know the smaller iterator, you can pass that to std::sort function.

Here is small illustration how to calculate distance:

#include <iostream>
#include <iterator>
#include <vector>

int main() {
    std::vector<int> v(100); //vector of size 100
    std::cout <<(std::distance(v.begin(), v.begin() + 10))<< std::endl;
    std::cout <<(std::distance(v.begin() +25, v.begin() +10))<< std::endl;
}

Output:

10
-15

Hope that gives you enough idea how to proceed to do what you want to.

Upvotes: 25

c-urchin
c-urchin

Reputation: 4504

To answer the question, std::distance() can be used to measure the distance to the begin() iterator, and these distances can then be compared. However, as pointed out by Ben, there are other problems with your code. See http://www.cplusplus.com/reference/std/iterator/distance/

Upvotes: 3

Ben Voigt
Ben Voigt

Reputation: 283624

After calling resize, all your existing iterators are invalid.

Furthermore, that line invokes undefined behavior, since you're both changing it_begin and reading from it, in an undetermined order.

Upvotes: 3

Related Questions