C++常用STL-排序

priority_queue

#include <iostream>
#include <queue>
#include <vector>

// 自定义比较函数,用于定义优先队列中的元素按照从小到大的顺序排列
struct Compare {
    bool operator()(const int& a, const int& b) const {
        return a > b; // 小顶堆,当 a 小于 b 时返回 true
    }
};

int main() {
    // 使用自定义的比较函数创建一个优先队列
    std::priority_queue<int, std::vector<int>, Compare> pq;

    // 插入元素
    pq.push(3);
    pq.push(1);
    pq.push(5);

    // 输出优先队列中的元素(从小到大)
    while (!pq.empty()) {
        std::cout << pq.top() << " ";
        pq.pop();
    }
    std::cout << std::endl;

    return 0;
}

std::sort

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

// 假设有一个类 Person,含有 id 和 name 两个字段
class Person {
public:
    int id;
    std::string name;

    Person(int id, const std::string& name) : id(id), name(name) {}
};

// 自定义比较函数,按照 id 字段进行排序
bool compareById(const Person& p1, const Person& p2) {
    return p1.id < p2.id;
}

int main() {
    std::vector<Person> people = {Person(2, "Alice"), Person(1, "Bob"), Person(3, "Charlie")};

    // 使用自定义比较函数对 people 容器中的元素按照 id 字段进行排序
    std::sort(people.begin(), people.end(), compareById);

    // 输出排序后的结果
    for (const auto& person : people) {
        std::cout << "id: " << person.id << ", name: " << person.name << std::endl;
    }

    return 0;
}

使用函数对象
#include <iostream>
#include <vector>
#include <algorithm>

// 假设有一个类 Person,含有 id 和 name 两个字段
class Person {
public:
    int id;
    std::string name;

    Person(int id, const std::string& name) : id(id), name(name) {}
};

// 自定义函数对象(仿函数),按照 id 字段进行排序
struct CompareById {
    bool operator()(const Person& p1, const Person& p2) const {
        return p1.id < p2.id;
    }
};

int main() {
    std::vector<Person> people = {Person(2, "Alice"), Person(1, "Bob"), Person(3, "Charlie")};

    // 使用函数对象对 people 容器中的元素按照 id 字段进行排序
    std::sort(people.begin(), people.end(), CompareById());

    // 输出排序后的结果
    for (const auto& person : people) {
        std::cout << "id: " << person.id << ", name: " << person.name << std::endl;
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值