Let\'s say I need to retrieve the median from a sequence of 1000000 random numeric values.
If using anything but std::list
, I have no (
Any random-access container (like std::vector
) can be sorted with the standard std::sort
algorithm, available in the
header.
For finding the median, it would be quicker to use std::nth_element
; this does enough of a sort to put one chosen element in the correct position, but doesn't completely sort the container. So you could find the median like this:
int median(vector &v)
{
size_t n = v.size() / 2;
nth_element(v.begin(), v.begin()+n, v.end());
return v[n];
}