重载运算符

  • c++中重载运算符是一个极重要的工具。
    虽然在OI中运用并不算太多,但在对于优先队列的运算、各种以结构体为基础的数据结构中,重载运算符有着其几乎无可替代的地方

格式

  • 以最常用的对于dijkstra堆优化为例。由于优先队列默认是大根堆,所以我们要将大于号重载为对于边权值的小于运算
struct edge
{
	int u,w;
};
bool operator < (const edge &x,const edge &y)
{
	return x.w>y.w;
}

直接写在里面也是可以的

struct edge
{
	int u,w;
	bool operator < (const edge &x) const
	{
		return w>x.w;
	}
};
特别注意一下const的位置

注意实际上如果你又要重载运算符又要写成小根堆,那么你应该重载的是大于号。

struct node{
    int u,v,w;
//    bool operator < (const node &y)const{return w<y.w;}
    bool operator > (const node &y)const{return w>y.w;}
};
priority_queue <node,vector<node>,greater<node>> t;
posted @ 2024-11-13 08:43  all_for_god  阅读(21)  评论(0)    收藏  举报