向量中 N 个最小值的索引

Mat*_* F. 1 c++ algorithm qt stl vector

我有一个QVector<float>,我需要从中获取一个指向最佳(最小)N 值的迭代器/指针数组。我该怎么做,最好使用 STL 算法?

Mat*_*usz 5

有一种简单的方法可以根据需要为您提供最佳 N 个索引(不仅是值)的向量
它与 Igor 的答案非常相似,但它为您提供了一个具有恰好 N 个最佳索引的结果向量。

这段代码非常简单,并且使用了STL的强大功能,就像您要求的那样。看一看:

QVector<int> findBestIndices(QVector<float> &times, 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(),
                     [&times](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;
}
Run Code Online (Sandbox Code Playgroud)

这将打印:

#1 => 0.29s
#4 => 2.39s
#0 => 3.14s
Run Code Online (Sandbox Code Playgroud)

尽管如此,如果您曾经想做同样的事情,但值就足够了……
您可以使用以下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';
Run Code Online (Sandbox Code Playgroud)