C++ priority_queue&algorithm

1.8 std::priority_queue

Cpp的标准库中std::priority_queue是一个模板类,用于实现优先级队列,其中的元素按照一定的优先级顺序进行排列,默认情况下,std::priority_queue使用大顶堆进行排序(即最大的元素优先)。使用std::priority_queue需要先包含头文件

#include <queue>

1.8.1 std::priority_queue的基本用法

1.定义元素类型:确定要存储在优先级队列中的元素类型。该类型必须支持比较操作符(),以便进行元素的排序。

struct MyElement {
    int priority;
    std::string name;
    // 其他成员...
};

2.定义比较函数或使用自定义比较器(可选):如果您的元素类型不是内置类型或没有默认的  操作符,您需要定义一个比较函数或使用自定义的比较器类来指定元素的优先级排序规则。

struct Compare {
    bool operator()(const MyElement& lhs, const MyElement& rhs) {
        return lhs.priority < rhs.priority;
    }
};

3.创建优先级队列对象:使用定义的元素类型和比较函数/比较器类,创建一个 std::priority_queue 对象。

MyElement element1{5, "First"};
MyElement element2{3, "Second"};

pq.push(element1);
pq.push(element2);

4.插入元素:使用 push 函数将元素插入优先级队列中。

std::priority_queue<MyElement, std::vector<MyElement>, Compare> pq;

5.访问顶部元素:使用 top 函数访问优先级队列中的最高优先级元素。

MyElement topElement = pq.top();

6.删除顶部元素:使用 pop 函数从优先级队列中删除最高优先级元素。

pq.pop();

通过重复执行步骤 5 和步骤 6,您可以顺序访问和删除优先级队列中的元素。

1.8.2 std::priority_queue的使用示例

#include <iostream>
#include <queue>
#include <string>

struct Task {
    int priority;
    std::string description;

    // 构造函数
    Task(int p, const std::string& desc) : priority(p), description(desc) {}
};

struct Compare {
    bool operator()(const Task& lhs, const Task& rhs) {
        return lhs.priority < rhs.priority;
    }
};

int main() {
    std::priority_queue<Task, std::vector<Task>, Compare> taskQueue;

    // 添加任务到队列
    taskQueue.push(Task(2, "Task 2"));
    taskQueue.push(Task(1, "Task 1"));
    taskQueue.push(Task(3, "Task 3"));

    // 处理任务
    while (!taskQueue.empty()) {
        Task currentTask = taskQueue.top();
        taskQueue.pop();

        std::cout << "Processing task: " << currentTask.description << std::endl;
    }

    return 0;
}

运行结果:

Processing task: Task 3
Processing task: Task 2
Processing task: Task 1

1.9 std::algorithm

Cpp的标准库中 std::algorithm 提供了许多使用的算法函数,用于处理容器(如 std::vector std::list 等)中的元素,这些算法函数可以用于查找、排序、转换、合并等操作。在使用 std::algorithm 之前,需要包含头文件
#include <algorithm>

1.9.1 algorithm中的常用函数

  • std::sort(),对容器进行排序
  • std::find(),返回查找容器中的值的迭代器,没有找到则返回容器::end()
  • std::copy(),将一个容器的元素复制到另一个容器中
  • std::reverse(),将容器中的元素进行反转
  • std::max(),返回比较值中的最大元素
  • std::max_element(),返回查找指定范围中的最大值所对应的迭代器
  • std::min(),返回比较值中的最小元素
  • std::min_element(),返回查找指定范围中的最小值所对应的迭代器
  • std::swap(),交换两个对象的值
1)std::sort()
函数原型:
template<class RandomAccessIterator>
void sort(
    RandomAccessIterator first,
    RandomAccessIterator last);

template<class RandomAccessIterator, class Compare>
void sort(
    RandomAccessIterator first,
    RandomAccessIterator last,
    Compare pred);
举例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> myV{ 3, 2, 1, 0, 5, 6, 9, 7, 8 };
    std::sort(myV.begin(), myV.end());
    for (int num : myV) {
        cout << num << " ";
    }
    return 0;
}
运行结果:
0 1 2 3 5 6 7 8 9
逆序排序:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool CompareReverse(int a, int b) {
    return a > b;
}

int main() {
    vector<int> myV{ 3, 2, 1, 0, 5, 6, 9, 7, 8 };
    //std::sort(myV.begin(), myV.end(), CompareReverse);   // 1.传入比较函数    
    std::sort(myV.begin(), myV.end(),                      // 2.使用Lambda匿名函数
        [](int a, int b) -> int {
            // 函数体
            return a > b;
        });
    for (int num : myV) {
        cout << num << " ";
    }
    return 0;
}
运行结果:
9 8 7 6 5 4 3 2 1 0
(2)std::find()
函数原型:
template<class InputIterator, class Type>
InputIterator find(
    InputIterator first,
    InputIterator last,
    const Type& value);
举例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v{ 1, 2, 3, 4, 5, 6, 7 };
    cout << *std::find(v.begin(), v.end(), 3) << endl;            // 1.查找元素3
    cout << bool(std::find(v.begin(), v.end(), 8) == v.end());    // 2.未找到元素8,返回v.end()
    return 0;
}
运行结果:
3
1
(3)std::copy()
函数原型:
template<class InputIterator, class OutputIterator>
OutputIterator copy(
    InputIterator first,
    InputIterator last,
    OutputIterator destBeg);
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> source{ 1, 2, 3, 4, 5, 6, 7 };
    vector<int> destination(source.size(),0);                // 确保destination能够容纳source的所有元素
    std::copy(source.begin(), source.end(), destination.begin());
    for (int num : destination) cout << num << " ";
    return 0;
}
运行结果:
1 2 3 4 5 6 7
(4)std::reverse()
函数原型:
template<class BidirectionalIterator>
void reverse(
    BidirectionalIterator first,
    BidirectionalIterator last);
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v1{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    std::reverse(v1.begin(), v1.end());
    for (int num : v1) cout << num << " ";
    return 0;
}
运行结果:
9 8 7 6 5 4 3 2 1
(5)std::max(), std::min()
函数原型:
template<class Type>
constexpr Type& max(
    const Type& left,
    const Type& right);

template<class Type>
constexpr const Type& min(
    const Type& left,
    const Type& right);
示例:
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    cout << "The max value of two is: " << std::max(4, 7) << endl;
    cout << "The max value of three is: " << std::max({ 3, 6, 9 });
    return 0;
}
运行结果:
The max value of two is: 7
The max value of three is: 9
(6)std::max_element(), std::min_element()
函数原型:
template<class ForwardIterator>
constexpr ForwardIterator max_element(
    ForwardIterator first,
    ForwardIterator last );

template<class ForwardIterator>
constexpr ForwardIterator min_element(
    ForwardIterator first,
    ForwardIterator last );
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    auto max_it = std::max_element(v1.begin(), v1.end());
    auto min_it = std::min_element(v1.begin(), v1.end());
    cout << "The max of v1 is: " << *max_it << endl;
    cout << "The min of v1 is: " << *min_it;
    return 0;
}
运行结果:
The max of v1 is: 9
The min of v1 is: 1
(7)std::swap()
函数原型:
template<class Type>
void swap(
    Type& left,
    Type& right);
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> myV{ 1, 2, 3, 4 };
    for (int i = 0, j = 1; i < myV.size(), j < myV.size(); i += 2, j += 2) {
        std::swap(myV[i], myV[j]);
    }
    for (int num : myV) {
        cout << num << " ";
    }

    return 0;
}
运行结果:
2 1 4 3

Reference

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值