How does this code find the center element in a vector?

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;
}
Last edited on
Is that code copied exactly from your book?

If so, I'd burn the book! The loop on lines 6-7 will only break if you force an error by entering a non-numeric value, which is bad form.

If you understand what iVec.begin() and iVec.size() do, you should be able to figure out how the iterator to the middle is obtained.

Andy
closed account (EwCjE3v7)
@andy

No, you can use ctrl+d on linux or ctrl+z on windows, nothing bad in that loop. It'll just stop until eof or if it fails.
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?
@Fr0zen1

Oops - forgot about ctrl-Z

But still think it's a poor form.

Andy
Topic archived. No new replies allowed.