Sorting half of vector - Syntax

Hi everyone.
I have read on my book that to sort an half of a vector I can write
sort(v.begin(),v.begin()+v.size())
It is a bit unclear. v.begin() points on the first element of the container but, to have the half size, the other bound shouldn't be v.begin()+v.size()/2 ? This way this expression it does equal to "0+N" so that N? (Where N = v.size() so that equals to v.end() - 1 ?

Thanks
Last edited on
Your book must have it wrong, or you have copied it wrong. For the code to compile you need to at least add parenthesis when you call the begin function the second time.
 
sort(v.begin(), v.begin() + v.size())
That code will do the same as
 
sort(v.begin(), v.end())
so it will sort the whole vector.

You are right that to sort the first half of the vector you can use
 
sort(v.begin(), v.begin() + v.size() / 2)
Last edited on
I missed the parenthesis, sorry!

Anyway in page 676 of C++ Programming Principles and Practice 2nd Edition the statement in the middle of the page are those (one meant for the first half and the other meant to second half). So I guess it is an erratum.

Thanks for mystery solved Peter87! :)
Topic archived. No new replies allowed.