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

后端 未结 10 928
再見小時候
再見小時候 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:03

    Here's a more complete version of Mike Seymour's answer:

    // Could use pass by copy to avoid changing vector
    double median(std::vector &v)
    {
      size_t n = v.size() / 2;
      std::nth_element(v.begin(), v.begin()+n, v.end());
      int vn = v[n];
      if(v.size()%2 == 1)
      {
        return vn;
      }else
      {
        std::nth_element(v.begin(), v.begin()+n-1, v.end());
        return 0.5*(vn+v[n-1]);
      }
    }
    

    It handles odd- or even-length input.

提交回复
热议问题