向量中N个最小值的指数

时间:2016-08-20 19:17:02

标签: c++ algorithm qt vector stl

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

2 个答案:

答案 0 :(得分:2)

这些方面的一些东西,也许是:

QVector<float> data;  // populated somehow
int N; // some value <= data.size()

std::vector<int> indices;
int i = 0;
std::generate_n(std::back_inserter(indices), data.size(),
  [&i]() { return i++; });

std::partial_sort(indices.begin(), indices.begin() + N, indices.end(),
  [&data](int ind1, int ind2) { return data[ind1] < data[ind2]; });
/* Now indices[0] through indices[N-1] contain indices
   of the N smallest elements in data. */

答案 1 :(得分:2)

有一种简单的方法可以根据需要为您提供最佳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;
}

这将打印:

#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';