I am working on an exercise where I have a vector and I am writing my own reverse algorithm by using a reverse and a normal (forward) iterator to reverse the content of the vector. However, I am not able to compare the iterators.
int vals[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
vector<int> numbers(vals, vals + 10);
vector<int>::iterator start = numbers.begin();
vector<int>::reverse_iterator end = numbers.rend();
I have a previous algorithm for reversing the vector by using two iterators, however in this task I am not able to compare them using the != operator between them. My guess would be to get the underlying pointers or indexes in the vector with each other but how do I get the pointers/index?
使用base()
返回的迭代器进行比较: it == rit.base() - 1
。
You can convert a reverse_iterator
to iterator
by calling base()
.
Be careful however, as there are some caveats. @Matthieu M.'s comment is particularly helpful:
Note:
base()
actually returns aniterator
to the element following the element that thereverse_iterator
was pointing to.
Checkouthttp://en.cppreference.com/w/cpp/iterator/reverse_iterator/base
rit.base()
returns a 'normal' iterator.
您可以使用(&*start == &*(end - 1))
直接比较迭代器指向的地址。
The two types cannot be compared (which is a very good idea) and calling .base()
is not very elegant (or generic) in my opinion. You can convert the types and compare the result. Taking into account the off-by-one rule involving reverse_iterators
.
Conversion from iterator
to reverse_iterator
need to be explicit (fortunately), however, conversion from reverse_iterator to iterator is not possible (unfortunately). So there is only one way to do conversion and then make the comparison.
std::vector<double> vv = {1.,2.,3.};
auto it = vv.begin();
auto rit = vv.rend();
// assert( it == rit ); // error: does not compile
assert(std::vector<double>::reverse_iterator{it} == rit);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.