📜  C++中的std :: nth_element(1)

📅  最后修改于: 2023-12-03 15:14:03.024000             🧑  作者: Mango

C++中的 std :: nth_element

简介

std::nth_element是C++ STL标头文件<algorithm>中的一个算法,用于在容器中找到第n个元素,使得该元素左边的元素(不包括该元素)都小于它,右边的元素(也不包括该元素)都大于它。这个算法的时间复杂度为O(n),并且不会改变容器的大小和内容。

语法
template< class RandomIt >
void nth_element( RandomIt first, RandomIt nth, RandomIt last );
template< class RandomIt, class Compare >
void nth_element( RandomIt first, RandomIt nth, RandomIt last, Compare comp );
参数
  • first, last - 需要排序的容器的范围。对于$n^{th}$ element算法,函数只对范围[first, last)中的元素执行操作。

  • nth – 指向需要确定位置的元素的迭代器。

  • comp - 可选参数,比较函数对象。默认情况下,使用 std::less<> 作为比较函数。

返回值

std::nth_element不会返回任何值,因为它没有对容器的内容进行修改。它改变了容器中元素的排序顺序以帮助确定目标元素的位置。

示例

示例一:

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

int main() {
    std::vector<int> numbers{ 1, 5, 3, 6, 4, 7, 2, 8 };
    std::nth_element(numbers.begin(), numbers.begin() + 4, numbers.end());
    std::cout << "The 4th element is " << numbers[4] << '\n';
    return 0;
}

输出:

The 4th element is 5

在上面的示例中,我们使用了std::nth_element来找到第4个元素。此操作后,容器中前四个元素将按升序排列。因此,第4个元素是5。

示例二:

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

struct Student {
    std::string name;
    float gpa;
};

int main() {
    std::vector<Student> students{
        {"Alice", 3.6},
        {"Bob", 3.2},
        {"Charlie", 3.8},
        {"David", 3.5},
        {"Ella", 3.9}
    };
    auto compareGPA = [](const Student& a, const Student& b) { return a.gpa < b.gpa; };
    std::nth_element(students.begin(), students.begin() + 2, students.end(), compareGPA);
    std::cout << "Top 3 students by GPA are:\n";
    for (int i = 0; i < 3; i++) {
        std::cout << students[i].name << " - " << students[i].gpa << '\n';
    }
    return 0;
}

输出:

Top 3 students by GPA are:
Charlie - 3.8
Ella - 3.9
Alice - 3.6

在上面的示例中,我们使用了std::nth_element来找到GPA排名前三的学生。我们使用了一个lambda函数来比较学生之间的GPA大小。

总结

在C++中,std::nth_element是用于在容器中查找第n个元素的非常有用的算法。它的时间复杂度为O(n),并且不会改变容器的大小和内容。除了使用默认的升序排序外,它还可以接受用户定义的比较函数。