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

后端 未结 10 960
再見小時候
再見小時候 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 11:16

    Here is an answer that considers the suggestion by @MatthieuM. ie does not modify the input vector. It uses a single partial sort (on a vector of indices) for both ranges of even and odd cardinality, while empty ranges are handled with exceptions thrown by a vector's at method:

    double median(vector const& v)
    {
        bool isEven = !(v.size() % 2); 
        size_t n    = v.size() / 2;
    
        vector vi(v.size()); 
        iota(vi.begin(), vi.end(), 0); 
    
        partial_sort(begin(vi), vi.begin() + n + 1, end(vi), 
            [&](size_t lhs, size_t rhs) { return v[lhs] < v[rhs]; }); 
    
        return isEven ? 0.5 * (v[vi.at(n-1)] + v[vi.at(n)]) : v[vi.at(n)];
    }
    

    Demo

提交回复
热议问题