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++ 编程中都非常常用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值