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

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

    Armadillo has an implementation that looks like the one in the answer https://stackoverflow.com/a/34077478 by https://stackoverflow.com/users/2608582/matthew-fioravante

    It uses one call to nth_element and one call to max_element and it is here: https://gitlab.com/conradsnicta/armadillo-code/-/blob/9.900.x/include/armadillo_bits/op_median_meat.hpp#L380

    //! find the median value of a std::vector (contents is modified)
    template
    inline 
    eT
    op_median::direct_median(std::vector& X)
      {
      arma_extra_debug_sigprint();
      
      const uword n_elem = uword(X.size());
      const uword half   = n_elem/2;
      
      typename std::vector::iterator first    = X.begin();
      typename std::vector::iterator nth      = first + half;
      typename std::vector::iterator pastlast = X.end();
      
      std::nth_element(first, nth, pastlast);
      
      if((n_elem % 2) == 0)  // even number of elements
        {
        typename std::vector::iterator start   = X.begin();
        typename std::vector::iterator pastend = start + half;
        
        const eT val1 = (*nth);
        const eT val2 = (*(std::max_element(start, pastend)));
        
        return op_mean::robust_mean(val1, val2);
        }
      else  // odd number of elements
        {
        return (*nth);
        }
      }
    

提交回复
热议问题