c++ - vector 中 N 个最小值的索引

标签 c++ algorithm qt vector stl

<分区>

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

最佳答案

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

这段代码非常简单,并且使用了 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

不过,如果你想做同样的事情,但值(value)就足够了......
您可以使用 std::partial_sort_copy 函数获得最佳元素的排序 vector :

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

关于c++ - vector 中 N 个最小值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39057855/

相关文章:

algorithm - 如何识别什么是尾递归,什么不是尾递归?

c++ - 在 64 位 Ubuntu 14.04 上为 32 位应用程序构建 QT (QJSValue : No such file or directory)

c++ - 没有新成员的 QTreeWidgetItem

c++ - 使用 double 的 sprintf 语句出错(缓冲区溢出?)

algorithm - 如何使用集合中的权重有效地一次随机挑选所有项目?

c++ - 无法将字符串转换为整数

python - 遍历一个 Spaghetti Stack 并返回到一棵树

c++ - 在 Windows 上使用 Qt Creator 设置缓存

c++ - 将具有结构初始化和赋值的 C 代码移至 C++ 编译器

c++ - 为什么我的代码无法读取 QTcpSocket 上可用的字节数?想法?