📅  最后修改于: 2023-12-03 15:13:44.943000             🧑  作者: Mango
STL(标准模板库)是C++中非常强大的工具集合,其中包含了各种有用的算法和容器。在STL中,sort()、partial_sort()和nth_element()+sort()是三种常用的排序算法。本文将介绍这三种算法的用法和特点。
sort()是STL中最常用的排序算法之一,用于对容器中的元素进行排序。其函数原型为:
template <class RandomAccessIterator>
void sort(RandomAccessIterator first, RandomAccessIterator last);
first
:容器中起始位置的迭代器last
:容器中结束位置的迭代器sort()算法使用的是快速排序(quicksort)算法,其时间复杂度平均为 O(nlogn)。它可以对容器中的所有元素进行排序,将它们按照默认的升序排列。
示例代码:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {3, 2, 1, 5, 4};
std::sort(numbers.begin(), numbers.end());
for (const auto& num : numbers) {
std::cout << num << " ";
}
return 0;
}
输出结果:
1 2 3 4 5
partial_sort()函数也用于对容器中的元素进行排序,但它仅对部分元素排序。其函数原型为:
template <class RandomAccessIterator>
void partial_sort(RandomAccessIterator first, RandomAccessIterator middle,
RandomAccessIterator last);
first
:容器中起始位置的迭代器middle
:容器中排序后中间位置之后的迭代器last
:容器中结束位置的迭代器这个函数将容器中的前 {middle - first} 个元素通过堆排序(heap sort)算法排序,保证前 {middle - first} 个元素是最小的元素。而 {middle - last} 个元素在容器中的位置是不确定的。
示例代码:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {3, 2, 1, 5, 4};
std::partial_sort(numbers.begin(), numbers.begin() + 3, numbers.end());
for (const auto& num : numbers) {
std::cout << num << " ";
}
return 0;
}
输出结果:
1 2 3 5 4
nth_element()函数用于寻找容器中第 n 小(或大)的元素,并将其放在正确的位置上,而不对其它元素进行排序。我们还可以结合sort()函数使用,将第 n 小(或大)的元素之后的元素排序。nth_element()函数的函数原型为:
template <class RandomAccessIterator>
void nth_element(RandomAccessIterator first, RandomAccessIterator nth,
RandomAccessIterator last);
first
:容器中起始位置的迭代器nth
:容器中第 n 小(或大)元素的迭代器last
:容器中结束位置的迭代器示例代码:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {3, 2, 1, 5, 4};
std::nth_element(numbers.begin(), numbers.begin() + 2, numbers.end());
std::sort(numbers.begin() + 2, numbers.end());
for (const auto& num : numbers) {
std::cout << num << " ";
}
return 0;
}
输出结果:
1 2 3 4 5
在上述示例中,我们使用nth_element()将第3小的元素(值为3)放置在正确的位置上,然后使用sort()对其之后的元素进行排序。
以上就是sort()、partial_sort()和nth_element()+sort()三种排序算法的介绍。在实际的编程任务中,根据具体的需求来选择合适的算法可以提高程序的性能和效率。