Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare vector<T>::iterator with vector<T>::reverse_iterator

Tags:

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?

like image 579
Martin Avatar asked Mar 04 '13 13:03

Martin


People also ask

How do you compare two iterators?

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 >, >=, <, <=.

How do you compare iterator values?

To compare the values that two iterators are pointing at, dereference the iterators first, and then use a comparison operator. Operator= -- Assign the iterator to a new position (typically the start or end of the container's elements).

What is a vector iterator?

An iterator is used to move thru the elements an STL container (vector, list, set, map, ...) in a similar way to array indexes or pointers. The * operator dereferences an iterator (ie, is used to access the element an iterator points to) , and ++ (and -- for most iterators) increments to the next element.

How do you iterate over a vector in reverse order?

So, to iterate over a vector in reverse direction, we can use the reverse_iterator to iterate from end to start. vector provides two functions which returns a reverse_iterator i.e. vector::rend() –> Returns a reverse iterator that points to the virtual element before the start of vector.


1 Answers

Do a comparison using the the iterator returned by base(): it == rit.base() - 1.

like image 97
wilx Avatar answered Oct 12 '22 01:10

wilx