priority_queue重写比较器

博客主要介绍了priority_queue在kruskalMST算法中的错误示范,并建议了正确用法。同时讲解了auto的原理,即根据后面的值推测前面的类型,还提及了其在遍历时的应用,涉及信息技术领域的C++编程知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

priority_queue

错误示范

#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<math.h>
#include<vector>
#include <fstream >
#include <ctime>
#include<string>
#include<queue>
using namespace std;
class Person
{
public:
	char* name;
	int id;
	int age;
	Person(const char* name, int id, int age)
	{
		this->name = new char[strlen(name) + 1];
		strcpy(this->name, name);
		this->id = id;
		this->age = age;
	}
	Person(const Person& person)
	{
		name= new char[strlen(person.name) + 1];
		strcpy(this->name, person.name);
		age=person.age;
		id = person.id;
	}

	Person& operator=(const Person& person)
	{
		
			name = new char[strlen(person.name) + 1];
			strcpy(this->name, person.name);
			age = person.age;
			id = person.id;
		
	}
	bool operator>(const Person& person)
	{
		if (this->id > person.id)
		{
			return false ;
		}
		return true;

	}
	bool operator>=(const Person& person)
	{
		if (this->id >= person.id)
		{
			return  false;
		}
		return true;

	}
	~Person()
	{
		if (this->name != NULL)
		{
			delete[]this->name;
			this->name = NULL;
		}
	}



};
int main()
{
	Person *student1 = new Person("A", 2, 23);
	Person *student2 = new Person("B", 3, 21);
	Person *student3 = new Person("C", 1, 22);
	if (*student1 > *student2)
	{
		cout << "1" << endl;
	}	
	priority_queue<Person*>q;
	q.push(student1);
	q.push(student2);
	q.push(student3);
	int size = q.size();
	for (int i = 0;i < size;i++)
	{
		cout << q.top()->name << endl;
		q.pop();
	}

}	
//只能比较三个数据有序
class Edge
{
public:
	int weight;
	Node* from;
	Node* to;
public:
	Edge(int weight, Node *from, Node *to)
	{
		this->weight = weight;
		this->to = to;
		this->from = from;
	}

};
struct cmp
{
	bool operator()(Edge *a, Edge *b)
	{
		if (a->weight == b->weight)  return a->weight >= b->weight;
		else return a->weight > b->weight;
	}
};

void test()
{
	Edge a(1,NULL,NULL);
	Edge b(2, NULL, NULL);
	Edge c(3, NULL, NULL);
	Edge d(100, NULL, NULL);
	Edge e(11, NULL, NULL);
	//只有重载priority_queue<Edge*> my_queq;
	priority_queue<Edge*,vector< Edge*>, cmp> my_queq;
	my_queq.push(&b);
	my_queq.push(&a);
	my_queq.push(&c);
	my_queq.push(&d);
	my_queq.push(&e);
	while (!my_queq.empty())
	{
		cout << my_queq.top()->weight << "  ";
		my_queq.pop();
	}
	cout << endl;
}
//这样写才能整体有序

但是在 kruskalMST算法却会出错

下列为错误代码

set<Edge*>* kruskalMST(Graph *graph)
	{
		mySet myset(graph->nodes);
		auto cmp2 = [](Edge* left, Edge* right) { return left->weight > right->weight; };
		priority_queue<Edge*, vector< Edge*>,cmp> mypr_que;
		
		for (set<Edge*>::iterator it = graph->edges->begin(); it != graph->edges->end(); it++)
		{
			cout << (*it)->weight << "  ";
			
			Edge* temp = (*it);
			mypr_que.push(temp);
		}
		cout<< endl;
	   set<Edge*>* result = new set<Edge*>;
		while (!mypr_que.empty())
		{
			Edge* edge = mypr_que.top();
			cout << "weight:"<<edge->weight << endl;
			mypr_que.pop();
			if (!myset.isSameSet(edge->from, edge->to))
			{
				result->insert(edge);
				myset.unionSet(edge->from, edge->to);
			}
		}
		return result;
		
	}

故我建议直接使用这种用法

使用auto

auto cmp2 = [](Edge* left, Edge* right) { return left->weight > right->weight; };
		priority_queue<Edge*, vector< Edge*>, decltype(cmp2)> mypr_que(cmp2);

auto介绍

auto的原理就是根据后面的值,来自己推测前面的类型是什么

遍历那会

  vector<int>v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    for(auto i : v){
        cout<<i<<" ";
    }
    cout<<endl;
    return 0;

### 使用 `std::priority_queue` 实现升序排列 默认情况下,`std::priority_queue` 是一个最大,即它会按照降序排列元素。为了实现升序排列,可以通过自定义比较函数来改变其行为。 #### 自定义比较器方法一:使用 lambda 表达式 通过传递带有特定逻辑的 lambda 函数作为第三个模板参数给 `std::priority_queue` 来构建一个小顶(升序),如下所示: ```cpp #include <iostream> #include <queue> int main() { // 定义一个小顶 (升序) std::priority_queue<int, std::vector<int>, decltype([](int a, int b){return a>b;})> minHeap; // 插入一些整数 minHeap.push(1); minHeap.push(3); minHeap.push(2); // 打印并移除所有元素 while(!minHeap.empty()){ std::cout << "Top element is : " << minHeap.top() << '\n'; minHeap.pop(); } return 0; } ``` #### 自定义比较器方法二:定义结构体重载运算符 另一种方式是创建一个新的类或结构体,并在其内部重写调用操作符 () ,从而指定两个对象之间的关系。这同样适用于建立小顶的情况: ```cpp struct CompareAscending { bool operator()(const int& lhs, const int& rhs) const{ return lhs > rhs; // 反转条件使得较小者具有更高优先级 } }; // ... std::priority_queue<int,std::vector<int>,CompareAscending> ascendingQueue; ascendingQueue.push(789); ascendingQueue.push(-456); ascendingQueue.push(123); while (!ascendingQueue.empty()) { std::cout << "Element with highest priority: " << ascendingQueue.top() << "\n"; ascendingQueue.pop(); } ``` 这两种方法都可以有效地让 `std::priority_queue` 按照从小到大的顺序处理数据[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值