【问题标题】:Indices of the N smallest values in a vector [closed]向量中 N 个最小值的索引
【发布时间】:2016-08-20 19:17:01
【问题描述】:

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

【问题讨论】:

  • 请定义“最佳”的含义(例如,最大值)。
  • 哦,我的意思是最小值。
  • 您使用的是哪个版本的 Qt?
  • 最好的方法是让你的QVector按升序排序,然后取第一个N值。
  • 听起来像是 std::nth_element 或者 std::partial_sort 的工作

标签: c++ algorithm qt vector stl


【解决方案1】:

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

【讨论】:

    【解决方案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. */
    

    【讨论】:

      猜你喜欢
      • 2012-12-17
      • 1970-01-01
      • 2022-01-10
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 2018-11-09
      • 1970-01-01
      相关资源
      最近更新 更多