我std::nth_element
用来获取向量百分位数的(大致正确)值,如下所示:
double percentile(std::vector<double> &vectorIn, double percent)
{
std::nth_element(vectorIn.begin(), vectorIn.begin() + (percent*vectorIn.size())/100, vectorIn.end());
return vectorIn[(percent*vectorIn.size())/100];
}
我注意到对于最多 32 个元素的 vectorIn 长度,向量会完全排序。从 33 个元素开始,它永远不会排序(如预期的那样)。
不确定这是否重要,但该函数位于通过 Matlab 使用“Microsoft Windows SDK 7.1 (C++)”编译的“(Matlab-)mex c++ 代码”中。
编辑:
另请参见传递给函数的 1e5 个向量中最长排序块的长度的以下直方图(向量包含 1e4 个随机元素并计算随机百分位数)。请注意非常小的值处的峰值。