What is the right approach when using STL container for median calculation?

后端 未结 10 929
再見小時候
再見小時候 2020-12-02 10:17

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 (

10条回答
  •  北海茫月
    2020-12-02 10:57

    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];
    }
    

提交回复
热议问题