The book I'm using tells me this code that makes an iterator point to the center element in a vector. I've been trying to figure out how it works though.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
std::vector<int> iVec;
int input(0);
while (std::cin >> input)
iVec.push_back(input);
std::vector<int>::iterator center = iVec.begin() + iVec.size() / 2;
std::cout << *center << std::endl;
return 0;
}
Actually I think I got it now. Let's say there is 5 elements. begin() points to the first one that is index 0.
I assume size() would have the value 5 since that's how many elements there is; but wouldn't that make the division by 2 rely on truncation since iterators don't have floating points?
0 + 5 / 2 would be 2.5, truncate it to 2, and you have the center element.
But since 0 doesn't really do anything couldn't we just use iVec.size() / 2?