Reputation:
I have two questions.
First question
I am reading about iterators in C++
from C++ primer 5th edition
book. In one of the code examples in this book, it is given that the following code snippet will find the middle element in the vector vi
auto mid = vi.begin() + vi.size() / 2;
Now I want to ask, why vi.begin()
is added in vi.size()
? Wouldn't vi.size()/2
be enough to find the middle element in vector vi
?
Second Question
auto mid = vi.begin() + vi.size() / 2;
In this code snippet, if I add parentheses around vi.begin() + vi.size()
like this:
auto mid = (vi.begin() + vi.size()) / 2;
It throws error that no "/" operator matches these operands...
Why does it throws this error? I ask this because logically this expression vi.begin() + vi.size()
should be calculated first and the result should get divided by 2
.
Please correct me if I am wrong.
Upvotes: 9
Views: 23649
Reputation: 23774
The expression vi.begin() + vi.size()
results in an iterator which has been incremented vi.size()
times, and iterators do not have an operator/
.
The reason the first snippet works is that the operator precedence rules of C++ mandates that vi.size() / 2
is calculated first, then the result of this (an integer) is added to vi.begin()
thus incrementing the iterator by the specified amount.
That is, the underlying misunderstanding is that vi.begin() + vi.size() / 2
is not equivalent to (vi.begin() + vi.size()) / 2
, but to vi.begin() + (vi.size() / 2)
.
Upvotes: 9
Reputation: 7017
Using the code:
auto mid = vi.begin() + vi.size() / 2;
Makes mid
an iterator to the middle element.
auto mid = (vi.begin() + vi.size()) / 2;
Does not make sense since iterators do not implement division.
The code vi.begin() + vi.size()
returns an iterator to the past-the-end element (v.end()
), which should not be divided by 2.
Upvotes: 2