C++的std::sort函数自定义排序

目录

使用普通函数(函数指针)

使用 Lambda 表达式

使用函数对象(仿函数)

自定义结构体(自定义类)排序


使用普通函数(函数指针)

对于常见的数据类型,可以传递一个普通的函数来进行自定义排序,接受两个元素并返回一个比较结果,通常返回 true 表示第一个元素小于第二个元素

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

bool customCompare(int a, int b) {
    return a < b;  // 升序排序
}

int main() {
    std::vector<int> vec = {5, 2, 8, 1, 3};

    // 使用自定义比较函数排序
    std::sort(vec.begin(), vec.end(), customCompare);

    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

使用 Lambda 表达式

C++11 引入了 Lambda 表达式,对于常见的数据类型,可以直接在 sort 调用中定义排序规则

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

int main() {
    std::vector<int> vec = {5, 2, 8, 1, 3};

    // 使用 Lambda 表达式进行升序排序
    std::sort(vec.begin(), vec.end(), [](int a, int b) {
        return a < b;  // 升序排序
    });

    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

使用函数对象(仿函数)

可以定义一个函数对象(即一个重载了 operator() 的类或结构体)来作为排序的比较器

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

class CustomCompare {
public:
    bool operator()(int a, int b) {
        return a > b;  // 降序排序
    }
};

int main() {
    std::vector<int> vec = {5, 2, 8, 1, 3};

    // 使用函数对象进行降序排序
    std::sort(vec.begin(), vec.end(), CustomCompare());

    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

自定义结构体(自定义类)排序

对于数据类型是自定义的结构体或者是自定义的类,可以使用自定义函数排序或者lambda表达式

自定义函数排序

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

struct Person {
    std::string name;
    int age;

    Person(std::string name, int age) : name(name), age(age) {}
};

bool compareByAge(const Person& a, const Person& b) {
    return a.age < b.age;  // 按年龄升序排序
}

int main() {
    std::vector<Person> people = {
        Person("Alice", 30),
        Person("Bob", 25),
        Person("Charlie", 35)
    };

    // 使用自定义的比较函数排序
    std::sort(people.begin(), people.end(), compareByAge);

    for (const auto& person : people) {
        std::cout << person.name << ": " << person.age << std::endl;
    }

    return 0;
}

lambda表达式

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

struct Person {
    std::string name;
    int age;

    Person(std::string name, int age) : name(name), age(age) {}
};

int main() {
    std::vector<Person> people = {
        Person("Alice", 30),
        Person("Bob", 25),
        Person("Charlie", 35)
    };

    // 使用 Lambda 表达式按年龄升序排序
    std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) {
        return a.age < b.age;  // 按年龄升序排序
    });

    for (const auto& person : people) {
        std::cout << person.name << ": " << person.age << std::endl;
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员萌芽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值