C++ 获取 vector 最大的 3 个数字

发布时间 2023-12-19 10:59:00作者: BuckyI

假设现在有一个数组存储了成绩信息,要获得前三名

#include <iostream>
#include <vector>
#include <algorithm>

std::vector<int> scores{10, 30, 90, 30, 100, 20, 10, 0, 30, 40, 40, 70, 70};

下面这种方法可以将前3名成绩复制到结果里,同时考虑到 scores 长度小于 3 的情况。

std::vector<int> result(scores.size() < 3 ? scores.size() : 3);
std::partial_sort_copy(scores.begin(), scores.end(), result.begin(), result.end(), std::greater<int>());

std::partial_sort_copy - cppreference.com
std::greater - cppreference.com

如果不介意对 scores 进行修改的话,可以这样做,std::sort 默认是升序排列,通过设定第三个参数指定排序依据。

std::sort(scores.begin(), scores.end(), [](int a, int b)
              { return a > b; }); // sort inversly
std::sort(scores.begin(), scores.end(), std::greater<int>()); // sort inversly (better approach)
int length = scores.size() > 3 ? 3 : scores.size();
for (auto c : std::vector<int>(scores.begin(), scores.begin() + length))
{
    std::cout << c << std::endl;
}

如果是只需要获取最大值:

int result = *std::max_element(scores.begin(), scores.end());