Compute Median of Values Stored In Vector - C++?(计算存储在向量中的值的中位数 - C++?)
问题描述
我是一名编程学生,对于我正在进行的一个项目,我必须做的事情之一是计算 int 值向量的中值.我将仅使用 STL 中的排序函数和向量成员函数(例如 .begin()、.end() 和 .size>)来执行此操作().
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 only the sort function from the STL and vector member functions such as .begin(), .end(), and .size().
我还应该确保我找到中位数,无论向量的值是奇数还是偶数.
I'm also supposed to make sure I find the median whether the vector has an odd number of values or an even number of values.
我卡住,下面是我的尝试.那么我哪里出错了?如果您愿意给我一些指示或资源以朝着正确的方向前进,我将不胜感激.
And I'm Stuck, below I have included my attempt. So where am I going wrong? I would appreciate if you would be willing to give me some pointers or resources to get going in the right direction.
代码:
int CalcMHWScore(const vector<int>& hWScores)
{
const int DIVISOR = 2;
double median;
sort(hWScores.begin(), hWScores.end());
if ((hWScores.size() % DIVISOR) == 0)
{
median = ((hWScores.begin() + hWScores.size()) + (hWScores.begin() + (hWScores.size() + 1))) / DIVISOR);
}
else
{
median = ((hWScores.begin() + hWScores.size()) / DIVISOR)
}
return median;
}
推荐答案
你正在做一个额外的划分,总体上使它比需要的更复杂一些.此外,当 2 在上下文中实际上更有意义时,就没有必要创建 DIVISOR.
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<int> 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];
}
}
}
这篇关于计算存储在向量中的值的中位数 - C++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:计算存储在向量中的值的中位数 - C++?
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
