Reputation: 83
So from what I learned to get the position of an iterator in a vector we do this:
it - vector.begin();
Can someone explain what this minus 'actually' does?
Upvotes: 0
Views: 631
Reputation: 238351
Presumably vector
is an instance of std::vector
and it
is an iterator to an element of that container.
Given two random access iterators to the same range, subtracting one from the other results in the distance from one element to their sibling. The result is same as if you would have subtracted the index of one element from the index of the other element.
The distance works like the number line: Distance from lower index to higher is negative.
begin
returns an iterator to the first element of a container. The index of the first element is 0. Thus, subtracting begin iterator from another iterator results in the distance of the other iterator from the beginning, which is the same as the index of the element pointed by the iterator.
Upvotes: 4