跳到正文

算法·理论

《论重载运算符的强大性能》

forever516约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年8月18日
收录
2025年12月12日
更新
2026年10月17日
篇幅
约 3 分钟

版本

  1. v1当前

加法

C++
struct node {
	int v;
};
node operator +(const node& a,const node& b) {
	node res;
	res.v=0;
	for(int i=1; i<=a.v; i++)res.v++;
	for(int j=1; j<=b.v; j++)res.v++;
	return res;
}//龟速加

使用经过这个东西加速“优化”的程序,在运行最朴素的加法时,时间复杂度可以来到优秀的O(a+b)O(a+b)。

C++
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	node a,b,c;
	cin>>a.v>>b.v;
	clock_t start = clock();
	c=a+b;
	cout<<c.v<<"\n";
	clock_t end = clock();
	double cpu_time_used = static_cast<double>(end - start) / CLOCKS_PER_SEC;
	std::cout << "CPU time used: " << cpu_time_used << " s\n";

	return 0;
}

我们输入一组较大的数据如a=1000000000,b=1000000000a=1000000000,b=1000000000,程序所运行时间来到了4.235s4.235s!

乘法

C++
node operator *(const node& a,const node& b) {
	node res;
	res.v=1;
	for(int i=1; i<=a.v; i++) {
		for(int j=1; j<=b.v; j++)res.v++;
	}
	return res;
}//龟速乘

使用经过这个东西加速“优化”的程序,在运行最朴素的乘法时,时间复杂度可以来到优秀的O(a×b)O(a \times b)。

依旧是上面那组数据,程序运行时间来到了31.7年。

这下,你可以直观感受到重载运算符的魅力了(原本C++内置的加法和乘法用时都是O(1)O(1),换句话说几乎用时为0ms)。

总的来说,对于算法萌新,以后一定要在代码前面加上:

C++
struct node {
	int v;
};
node operator *(const node& a,const node& b) {
	node res;
	res.v=1;
	for(int i=1; i<=a.v; i++) {
		for(int j=1; j<=b.v; j++)res.v++;
	}
	return res;
}//龟速乘
node operator +(const node& a,const node& b) {
	node res;
	res.v=0;
	for(int i=1; i<=a.v; i++)res.v++;
	for(int j=1; j<=b.v; j++)res.v++;
	return res;
}//龟速加
int sp(int x,int k) {
	int ans=1;
	for(int i=1; i<=k; i++) {
		ans=ans*x;
	}
	return ans;
}//龟速幂

如此,你的程序以后一定能题题都是最优解!

原文