【发布时间】:2020-01-09 15:51:36
【问题描述】:
我希望从 C++ 中的浮点数组中计算中值:
float Median( FloatArray const * constFloatArray )
{
FloatArray scratch = FloatArray( *constFloatArray );
int64_t const size = scratch.GetWidth() * scratch.GetHeight();
int64_t const mid = size / 2;
std::nth_element( scratch.begin(), scratch.begin() + mid, scratch.end() );
return scratch[ mid ];
}
FloatArray 包含一个常规的 C++ 浮点数数组。
我正在使用std::nth_element,但想知道是否有像nth_element 这样的设施可以处理const 数据?现在,我正在制作一个副本,然后在扔掉副本之前做nth_element。如果const 数据没有类似nth_element 的内容,是否有更有效的方法使用复制步骤来计算信息,从而避免潜在的额外 O(n) 循环?也许性能影响可以忽略不计?我的数组大小可能在 20 亿左右。
【问题讨论】:
-
您可能想研究一些不会修改源代码的其他算法,例如:stackoverflow.com/questions/10930732/…
-
您也许可以调整
nth_element算法以同时复制元素(stackoverflow.com/questions/29145520/…),但我怀疑它会明显更快。如果您进行性能比较,看看结果会很有趣。 -
在不使用 o(n) 额外空间改变输入的情况下选择中位数是不可能的,因此它不是非修改算法的自然候选者;副本也没有明显的用途。
标签: c++ constants nth-element