Compare Iterators, C ++

Is it possible to compare two iterators? Comparison 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 to compare?

+5
source share
4 answers

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

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

Here is a small illustration of how to calculate the 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;
}

Conclusion:

10
-15

, , , .

+14

, std:: distance() begin(), . , , . . http://www.cplusplus.com/reference/std/iterator/distance/

+3

resize .

, undefined, it_begin .

+2

++ Primer 5th Ed. .111, 3.4.2. :

== != .

The section also indicates that iterators for relational operators of strings and vectors (aka iterator arithmetic), which include>,> =, <, <=.

+1
source

All Articles