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 )
{
....
开发者_StackOverflow社区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?
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.
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 >, >=, <, <=.
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/
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.
精彩评论