当前位置: 首页 > article >正文

priority_queue的创建_结构体类型(重载小于运算符)c++

当优先级队列里面存的是一个自定义(结构体)类型,我们有两种方式,一个是用内置类型的方式,在priority_queue<>里写三个参数,比如int, vector<int>, less<int>,把int改成结构体的名字就可以了,但此时就不能用less了,因为less默认是对内置类型使用的,如果less<>里面写自定义类型,还需要写小于号重载运算符的,不然会报错,如果你不想用less,你自己在重新写一个比较方法才行,greater同理,所以如果是结构体的话,我们按照less写法有点麻烦

用第二种写法,在结构体中直接重载小于号运算符,直接把创建出来的结构体,放到优先级队列里,就可以创建出相应的大小根堆

#include <iostream>
#include <queue>
using namespace std;

struct node {
	int a, b, c;

	//重载<运算符
	//按照b为基准,创建大根堆
	//bool operator<(const node& x) const //最后面的const表示这个函数是一个常量成员函数
	//{
	//	return b < x.b;
	//}

	//小根堆,把<改成>就可以了
	bool operator<(const node& x) const
	{
		return b > x.b;
	}
};

void test()
{
	//如果选择重载小于运算符的话,创建堆的时候直接把node放进来就可以了
	priority_queue<node> heap;

	for (int i = 1; i <= 5; ++i)
	{
		heap.push({ i + 5, i + 1, i + 2 });
	}

	while (heap.size())
	{
		node t = heap.top(); heap.pop();
		cout << t.a << " " << t.b << " " << t.c << endl;
	}
}

int main()
{
	test();

	return 0;
}
输出:
6 2 3
7 3 4
8 4 5
9 5 6
10 6 7

其实我们掌握了重载小于运算符,也会重载大于运算符,这些就够了,感兴趣也可以看看第一种less写法,也是写个小于重载,greater在实现个大于重载运算符

#include <iostream>
#include <queue>
using namespace std;

struct node {
	int a, b, c;

	//less 大根堆
	bool operator<(const node& x) const { return b < x.b; }

	//greater 小根堆
	bool operator>(const node& x) const { return b > x.b; }
};


void test2()
{
	//小根堆
	priority_queue<node, vector<node>, greater<node>> heap;

	for (int i = 1; i <= 5; ++i)
	{
		heap.push({ i + 5, i + 1, i + 2 });
	}

	while (heap.size())
	{
		node t = heap.top(); heap.pop();
		cout << t.a << " " << t.b << " " << t.c << endl;
	}
}

int main()
{
	test2();

	return 0;
}

输出:
6 2 3
7 3 4
8 4 5
9 5 6
10 6 7


http://www.kler.cn/a/526957.html

相关文章:

  • 服务器虚拟化技术详解与实战:架构、部署与优化
  • AJAX综合案例——图书管理
  • ubuntu20.04.6下运行VLC-Qt例子simple-player
  • Deepseek技术浅析(二):大语言模型
  • 留学生scratch计算机haskell函数ocaml编程ruby语言prolog作业VB
  • 新版231普通阿里滑块 自动化和逆向实现 分析
  • 计算机网络之计算机网络协议、接口、服务等概念
  • 【MyDB】4-VersionManager 之 2-事务的隔离级别
  • pytorch实现半监督学习
  • CSS入门知识
  • VUE之组件通信(一)
  • win11本地部署 DeepSeek-R1 大模型!免费开源,媲美OpenAI-o1能力,断网也能用
  • 【数据机构】_复杂度
  • 【leetcode详解】T3175(一点反思)
  • arm-linux-gnueabihf安装
  • Retrieval-Augmented Generation for Large Language Models: A Survey——(1)Overview
  • 数据库性能优化(sql优化)_SQL执行计划03_yxy
  • Chapter 3-19. Detecting Congestion in Fibre Channel Fabrics
  • VS安卓仿真器下载失败怎么办?
  • maven mysql jdk nvm node npm 环境安装
  • KNIME:开源 AI 数据科学
  • Janus-Pro 论文解读:DeepSeek 如何重塑多模态技术格局
  • 【Block总结】ODConv动态卷积,适用于CV任务|即插即用
  • 全网多平台媒体内容解析工具使用指南
  • Java锁自定义实现到aqs的理解
  • 007 JSON Web Token