关于结构体内嵌比较函数后,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;
}
发布了3 篇原创文章 · 获赞 1 · 访问量 1239

猜你喜欢

转载自blog.csdn.net/Ryn_love/article/details/104857554