For the reverse iterator, it is very important to figure out the difference between the logical location and the actual location.
The position and value of the reverse iterator are displayed:
It can be found that the Position (actual location) indicated by the reverse iterator is different from the value (logical location or value. C ++ does this for some reason. The cause of this behavior is the half-open interval. To be able to define all elements in the container, we must use the next position of the last element. However, for the reverse iterator, this position is located before the first element. At this time, the problem occurs. This location may not exist because the container does not require the location before the first element to be valid. Www.2cto.com
Therefore, the reverse iterator uses a small trick: in fact, the "half open principle" is put upside down, that is, the range defined by the reverse iterator does not include the start point, but the end point. However, the logic is normal. As a result, the positions of the elements actually referred by the reverse iterator are inconsistent with those in the logic.
Next let's look at the process of converting an iterator into a reverse iterator:
It can be found that the actual position (element) of the iterator remains unchanged, but the logical position (element) changes. In the figure, the actual position after the pos iterator is converted to the reverse iterator rpos is 5, but the logical position is 4. That is, the logical element position is the first position of the actual position. Test code:
[Cpp]
# Include <iostream>
# Include <vector>
# Include <algorithm>
Using namespace std;
Int main ()
{
Vector <int> coll;
// Insert elements from 1 to 9
For (int I = 1; I <= 9; ++ I ){
Coll. push_back (I );
}
// Find position of element with value 5
Vector <int>: iterator pos;
Pos = find (coll. begin (), coll. end (),
5 );
// Print value to which iterator pos refers
Cout <"pos:" <* pos <endl;
// Convert iterator to reverse iterator rpos
Vector <int>: reverse_iterator rpos (pos );
// Print value to which reverse iterator rpos refers
Cout <"rpos:" <* rpos <endl;
}
# Include <iostream>
# Include <vector>
# Include <algorithm>
Using namespace std;
Int main ()
{
Vector <int> coll;
// Insert elements from 1 to 9
For (int I = 1; I <= 9; ++ I ){
Coll. push_back (I );
}
// Find position of element with value 5
Vector <int>: iterator pos;
Pos = find (coll. begin (), coll. end (),
5 );
// Print value to which iterator pos refers
Cout <"pos:" <* pos <endl;
// Convert iterator to reverse iterator rpos
Vector <int>: reverse_iterator rpos (pos );
// Print value to which reverse iterator rpos refers
Cout <"rpos:" <* rpos <endl;
}
The output result is (VS2008 ):