Compute Median of Values Stored In Vector - C++?

后端 未结 6 664
故里飘歌
故里飘歌 2020-11-29 03:40

I\'m a programming student, and for a project I\'m working on, on of the things I have to do is compute the median value of a vector of int values. I\'m to do this using onl

6条回答
  •  广开言路
    2020-11-29 03:50

    You are doing an extra division and overall making it a bit more complex than it needs to be. Also, there's no need to create a DIVISOR when 2 is actually more meaningful in context.

    double CalcMHWScore(vector scores)
    {
      size_t size = scores.size();
    
      if (size == 0)
      {
        return 0;  // Undefined, really.
      }
      else
      {
        sort(scores.begin(), scores.end());
        if (size % 2 == 0)
        {
          return (scores[size / 2 - 1] + scores[size / 2]) / 2;
        }
        else 
        {
          return scores[size / 2];
        }
      }
    }
    

提交回复
热议问题