sort和swap函数
在 C++ 中,sort
和 swap
是两个非常实用的函数,下面为你详细介绍它们。
sort
函数
功能
sort
函数定义在 <algorithm>
头文件中,用于对容器内的元素进行排序,默认使用的是升序排序,其底层实现通常是基于快速排序、堆排序和插入排序的混合算法,时间复杂度平均为 O(nlogn)。
函数原型
cpp
// 对 [first, last) 范围内的元素进行排序,使用 operator< 进行比较
template< class RandomIt >
void sort( RandomIt first, RandomIt last );// 对 [first, last) 范围内的元素进行排序,使用给定的比较函数 comp
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
示例代码
cpp
#include <iostream>
#include <algorithm>
#include <vector>int main() {std::vector<int> numbers = {5, 2, 9, 1, 5, 6};// 默认升序排序std::sort(numbers.begin(), numbers.end());std::cout << "升序排序结果: ";for (int num : numbers) {std::cout << num << " ";}std::cout << std::endl;// 使用自定义比较函数进行降序排序std::sort(numbers.begin(), numbers.end(), [](int a, int b) {return a > b;});std::cout << "降序排序结果: ";for (int num : numbers) {std::cout << num << " ";}std::cout << std::endl;return 0;
}
代码解释
- 首先,包含了必要的头文件
<iostream>
、<algorithm>
和<vector>
。 - 定义了一个
std::vector<int>
类型的容器numbers
,并初始化了一些元素。 - 调用
std::sort(numbers.begin(), numbers.end())
对容器中的元素进行升序排序。 - 调用
std::sort(numbers.begin(), numbers.end(), [](int a, int b) { return a > b; })
使用自定义的 lambda 函数作为比较函数,对容器中的元素进行降序排序。
swap
函数
功能
swap
函数同样定义在 <algorithm>
头文件中,用于交换两个对象的值。
函数原型
cpp
// 交换两个对象的值
template< class T >
void swap( T& a, T& b );
示例代码
cpp
#include <iostream>
#include <algorithm>int main() {int a = 10;int b = 20;std::cout << "交换前: a = " << a << ", b = " << b << std::endl;std::swap(a, b);std::cout << "交换后: a = " << a << ", b = " << b << std::endl;return 0;
}
代码解释
- 包含了必要的头文件
<iostream>
和<algorithm>
。 - 定义了两个整型变量
a
和b
,并分别初始化为 10 和 20。 - 调用
std::swap(a, b)
交换a
和b
的值。 - 输出交换前后
a
和b
的值。
综上所述,sort
函数用于对容器内的元素进行排序,而 swap
函数用于交换两个对象的值,它们在 C++ 编程中都非常常用。