Re: why std::deque::rbegin() - rend() gives a negative number?
On Sep 12, 7:00 am, zhangy...@yahoo.com.cn wrote:
On 9?12?, ??12?06?, Peng Yu <PengYu...@gmail.com> wrote:
I don't understand why rbegin() - rend() gives a negative
number.
Do you have to increment or decrement rbegin() to get to rend()?
Since rbegin() + 1 gives the one before the last element, I
think rbegin() - rend() should give a positive number.
rbegin() and rend() return iterators. The difference between
iterators is the number of times you have to increment
(positive difference) or decrement (negative difference) the
first iterator to get to the second. Iterators don't
(necessarily) designate elements in a container; they designate
elements in a sequence. In the case of reverse iterators, the
sequence has the opposite order as the sequence of the
underlying iterators.
#include <deque>
#include <iostream>
int main() {
std::deque<double> q;
q.push_back(1);
q.push_front(0);
q.push_back(2);
q.push_back(3);
std::cout << q[0] << std::endl;
std::cout << q.rbegin() - q.rend() << std::endl;//gives a negative
number?
std::cout << *(q.rbegin() + 1) << std::endl;// gives the one before
the last element
}- ??????? -
- ??????? -
that's right, rbegin() - rend() gives a negative number indeed
given a vector that have 5 elements,
rbegin() refers to the last element, and rend() refers to the
first element, so
rbegin() + 4 = rend()
If the vector has five elements, that must be rbegin() + 5 ==
rend(). (His vector only has four elements.)
then rbegin - rend() = -4
the result(-4) is negative
The results of rend() - rbegin() should be the number of
elements in the vector. The results of rbegin() - rend() should
be the negation of this.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34