有一种简单的方法可以根据需要为您提供最佳 N 个索引的向量(不仅是值)。
它与 Igor 的答案非常相似,但它为您提供了一个具有恰好 N 个最佳索引的结果向量。
此代码非常简单,并且使用了 STL 的强大功能,正如您所要求的那样。看看:
QVector<int> findBestIndices(QVector<float> ×, const int &N)
{
QVector<int> indices(times.size());
std::iota(indices.begin(), indices.end(), 0); // fill with 0,1,2,...
std::partial_sort(indices.begin(), indices.begin()+N, indices.end(),
[×](int i,int j) {return times[i]<times[j];});
return QVector<int>(indices.begin(), indices.begin()+N);
}
int main()
{
QVector<float> times = {3.14, 0.29, 3.50, 59.38, 2.39};
const int N = 3; // N best times
QVector<int> best = findBestIndices(times, N);
for(const auto &index : best) {
std::cout << '#' << index << " => " << times[index] << "s\n";
}
return 0;
}
这将打印:
#1 => 0.29s
#4 => 2.39s
#0 => 3.14s
不过,如果您也想这样做,但价值观就足够了...
您可以使用std::partial_sort_copy 函数获得最佳元素的排序向量:
const int N = 3;
QVector<float> best(N);
QVector<float> times = {3.14, 0.29, 3.50, 59.38, 2.39};
std::partial_sort_copy(times.begin(), times.end(), best.begin(), best.end());
for(const auto &mytime : best) std::cout << mytime << '\n';