简体   繁体   中英

What does it - vector.begin() actually do?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM