目录
前言
当看到一些题解时,会发现优秀的解法有时候会出现数据结构中加重载函数operator的情况,故而我详细了解了一下此函数的用法及举例一些案例
一、重载函数operator是什么?
operator 是 C++ 的一个关键字,它和运算符(如 =)一起使用,表示一个运算符重载函数,在理解时可将 operator 和待重载的运算符整体(如 operator=)视为一个函数名。
使用 operator 重载运算符,是 C++ 扩展运算符功能的方法。使用 operator 扩展运算符功能的原因如下:
使重载后的运算符的使用方法与重载前一致;
扩展运算符的功能只能通过函数的方式实现。(实际上,C++ 中各种“功能”都是通过函数实现的)
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/liitdar/article/details/80654324
operator重载运算符的结构介绍
<返回类型说明符> operator <运算符符号>(<参数表>) { <函数体> }
关于这一点在https://liitdar.blog.csdn.net/的文章中已经讲的非常清楚了,希望大家可以从中得到帮助。
二、在数据结构中的使用
1.使结构体可以互相相加减
代码如下(示例):
#include<bits/stdc++.h>
using namespace std;
const int N = 1000010;
struct node{
int x, y;
//返回值int
int operator +(const node &e)const {
// 返回结果, 这里的+号为int间的+号,也就是普通的+号
return e.x + x + e.y + y;
}
}f[N];
int main()
{
f[1].x = 2, f[1].y = 10;
f[2].x = 3, f[2].y = 11;
// node之间的+以重载,返回值int
int res = f[1] + f[2];
cout << res <<endl;
return 0;
}
输出结果: 26
解释: 相加的结果类型为填写+返回值的类型也就是int,相加规则:2+3+10+11
2.使结构体可以进行比较代替cmp(另写比较函数)
代码如下(示例):
#include<bits/stdc++.h>
using namespace std;
const int N = 1000010;
struct node{
int x, y;
//用于比较大小返回值bool
bool operator < (const node &e) const{
if(e.x != x) return x < e.x;
return y < e.y;
}
}f[N];
int main()
{
srand(time(0));
cout << "排序前: " << endl;
for(int i = 1; i <= 5; i++)
{
// 生成0-9随机数
f[i].x = rand() % 10; f[i].y = i;
cout << f[i].x << " " << f[i].y << endl;
}
// 排序下标从1开始到5
sort(f + 1, f + 1 + 5);
cout << "排序后: "<<endl;
for(int i = 1; i <= 5; i++)
cout << f[i].x << " " << f[i].y << endl;
return 0;
}
排序前:
5 1
4 2
4 3
0 4
7 5
排序后:
7 5
5 1
4 2
4 3
0 4
总结
提示:算法竞赛常用的函数,真的必须掌握hh。