Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 815
Johnas Avatar asked Apr 30 '11 15:04

Johnas


1 Answers

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.

like image 169
Nawaz Avatar answered Oct 07 '22 18:10

Nawaz