Q-bertsuit Q-bertsuit - 1 month ago 18
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;
v.push_back(1);
v.push_back(2);
v.push_back(3);

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

"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;
test.push_back(1);
  test.push_back(2);
int d = test.begin() - test.end();
cout << d;
return 0;

says : -2