S
subramanian100in
Consider the following program x.cpp:
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> c;
for (int i = 0; i != 10; ++i)
c.push_back(i);
cout << c.end() - c.begin() << endl;
cout << c.rend() - c.rbegin() << endl;
return EXIT_SUCCESS;
}
I compiled with g++3.4.3 as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp
When I ran it, it produced the output
10
10
The first 10 in the output is fine. It corresponds to c.end() - c.begin
().
Shouldn't the second 10 in the output be -10 because I am using
reverse iterators in calculating c.rend() - c.rbegin() ie isn't this
expression equivalent to c.begin() - c.end() in which case -10 would
be printed? Is my understanding wrong ?
Is the difference operator-() between the RandomAccessIterators
defined in <iterator> ? If so, how does the program compile even when
I do not #include <iterator> ?
Kindly clarify.
Thanks
V.Subramanian
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> c;
for (int i = 0; i != 10; ++i)
c.push_back(i);
cout << c.end() - c.begin() << endl;
cout << c.rend() - c.rbegin() << endl;
return EXIT_SUCCESS;
}
I compiled with g++3.4.3 as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp
When I ran it, it produced the output
10
10
The first 10 in the output is fine. It corresponds to c.end() - c.begin
().
Shouldn't the second 10 in the output be -10 because I am using
reverse iterators in calculating c.rend() - c.rbegin() ie isn't this
expression equivalent to c.begin() - c.end() in which case -10 would
be printed? Is my understanding wrong ?
Is the difference operator-() between the RandomAccessIterators
defined in <iterator> ? If so, how does the program compile even when
I do not #include <iterator> ?
Kindly clarify.
Thanks
V.Subramanian