关于结构体内嵌比较函数后,sort排序和优先队列内元素的顺序

关于结构体内嵌比较函数后的排序规则,见如下代码注释

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

const int MAX = 1000;

struct Node_t {
	int val;
	Node_t(int x) :val(x) {};
	bool operator<(const Node_t x)const {//重定义了结构体类型的默认排序方式,没有这个比较函数,默认排序方式是从小到大
		return val > x.val;
	}
};

vector<Node_t> node;

bool Compare(Node_t x, Node_t y) {
	return x.val < y.val;
}

int main() {
	//输入
	for (int i = 0; i < 5; i++) {
		node.push_back(Node_t(rand()%100));
	}
	//打印
	for (int i = 0; i < 5; i++) {
		printf("%d ", node[i].val);
	}
	printf("\n");
	//把所有元素加入优先队列后输出
	priority_queue<Node_t> myQueue;//优先队列主要通过堆排序实现,它的自动排序
	//将按照与变量类型的默认方式相反的顺序进行排序,比如此时结构体类型的默认方
	//式是从大到小,而优先队列的排序方式就是从小到大(小顶堆);
	for (int i = 0; i < 5; i++) {
		myQueue.push(node[i]);
	}
	printf("priority_queue:");
	while (!myQueue.empty()) {
		printf("%d ", myQueue.top().val);
		myQueue.pop();
	}
	printf("\n");
	//按默认方式排序后打印
	sort(node.begin(),node.end());//按照按照变量类型的默认方式进行排序
	printf("default sort:");
	for (int i = 0; i < 5; i++) {
		printf("%d ", node[i].val);
	}
	printf("\n");
	//按Compare比较函数排序后打印
	sort(node.begin(), node.end(), Compare);
	printf("Function Compare:");
	for (int i = 0; i < 5; i++) {
		printf("%d ", node[i].val);
	}
	printf("\n");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C++中,我们可以通过自定义比较函数来实现自定义优先队列排序比较函数是一个返回布尔值的函数,用于确定元素的优先级。在优先队列中,元素按照默认的排序规则进行排序,即大根堆或小根堆。默认情况下,元素按照从大到小的顺序排列,也就是大根堆。如果要实现不同的排序规则,我们可以自定义比较函数来改变元素排序顺序。 下面是一个示例代码,展示了如何在C++中自定义优先队列排序: ```cpp #include <iostream> #include <queue> using namespace std; // 自定义比较函数,实现从小到大的排序规则 struct Compare { bool operator() (int a, int b) { return a > b; } }; void custom_priority_queue_sort() { int source_data = {3, 5, 8, 1, 10, 2, 9, 15, 13, 16}; priority_queue<int, vector<int>, Compare> q; // 使用自定义的比较函数 for (auto n : source_data) q.push(n); while (!q.empty()) { cout << q.top() << endl; q.pop(); } } int main() { custom_priority_queue_sort(); return 0; } ``` 在上述代码中,我们定义了一个名为`Compare`的结构体,其中重载了小括号运算符`()`。在自定义的比较函数中,我们将元素按照从小到大的顺序排列,即返回`a > b`。然后在创建优先队列时,我们通过指定自定义比较函数`Compare`来改变排序规则。 运行以上代码,输出结果为: ``` 1 2 3 5 8 9 10 13 15 16 ``` 以上代码演示了如何在C++中自定义优先队列排序规则。通过自定义比较函数,我们可以实现各种不同的排序方式来满足特定需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Milk_exe

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

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

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

打赏作者

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

抵扣说明:

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

余额充值