Q-bertsuit Q-bertsuit - 1 year ago 97
C++ Question

Operators of std::iterator

I have assumed that iterators had overloaded their operator+ and operator- to return an iterator. I also assumed that iterators had overloaded operator int(), which made the following compile:

std::vector<int> v;

std::vector<int>::iterator low = std::lower_bound(v.begin(), v.end(), 2);

int i = low - v.begin();

But when I tried assigning the result to an iterator instead of an int i got a compile error:

std::vector<int>::iterator i = low - v.begin();

Why doesnt subtracting an iterator from another result in an iterator?

I cant find any information on cplusplus.com/reference or anywhere else on exactly what the interface of an iterator contains.

Answer Source

"Why doesnt subtracting an iterator from another result in an iterator?"

Why would it, subtracting 2 pointers does not result in another pointer.

If anything I would expect it to return the distance between the 2 iterators in units of contained elements - ie an int

and a quick test shows that it does return the distance

vector<int> test;
int d = test.begin() - test.end();
cout << d;
return 0;

says : -2

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download