sort and binary_search are two of a family. The C++ library has a shelf of
small, fast, well-tested functions for the things you keep writing loops for:
the smallest element, how many sevens, the sum, the first zero. Knowing them
saves time and, more importantly, bugs. They all take the same two arguments
you already know: where to start and where to stop.
The toolbox
For 4 7 -2 9 0 7 -2 3 it prints min -2 at 2, max 9 at 3, sevens 2,
sum 26 and first zero at 4. Three things to notice:
min_element,max_elementandfindreturn a position, not a value — the same kind of thing asa.begin().*lowreads the value at that position, andlow - a.begin()turns it into an index.autolets the compiler name the type, which is long and never worth typing.- When
findfinds nothing, it returnsa.end(), the position past the last element. Compare witha.end()before reading*it. accumulate(a.begin(), a.end(), 0LL)adds everything to a starting value — and the sum has the type of that value. With a plain0the sum is anint, and 10⁵ numbers of 10⁵ overflow it.0LLmakes it along long.
| Function | Gives |
|---|---|
min_element(b, e), max_element(b, e) | the position of the smallest / largest (the first one, if equal) |
count(b, e, x) | how many elements equal x |
find(b, e, x) | the position of the first , or |