5 份代码,让你彻底搞懂 std::swap() 在干嘛

1

int a,b,*c,*d;
signed main(){ios::sync_with_stdio(false),cin.tie(nullptr);
	a=1,b=2;
	c=&a,d=&b;
	cout<<a<<" "<<b<<" "<<*c<<" "<<*d<<endl;
	swap(a,b);
	cout<<a<<" "<<b<<" "<<*c<<" "<<*d<<endl;
return 0;}

结果为

1 2 1 2
2 1 2 1

说明 swap 不是交换指针,而是内存内容的改变。

2

#define N 10000000
int a[N],b[N],*c,*d;
signed main(){ios::sync_with_stdio(false),cin.tie(nullptr);
	fill(a,a+N,1);
	fill(b,b+N,2);
	c=a,d=b;
	cout<<a[0]<<" "<<b[0]<<" "<<c[0]<<" "<<d[0]<<endl;
	swap(a,b);
	cout<<a[0]<<" "<<b[0]<<" "<<c[0]<<" "<<d[0]<<endl;
return 0;}

结果为

1 2 1 2
2 1 2 1

说明数组的 swap 也不是交换指针,而是内存内容的改变。

所以一次 swap 的复杂度是数组长度的,请注意。

3

#define N 10000000
int a[N],b[N],*c,*d;
signed main(){ios::sync_with_stdio(false),cin.tie(nullptr);
	fill(a,a+N,1);
	fill(b,b+N,2);
	c=a,d=b;
	cout<<a[0]<<" "<<b[0]<<" "<<c[0]<<" "<<d[0]<<endl;
	swap(c,d);
	cout<<a[0]<<" "<<b[0]<<" "<<c[0]<<" "<<d[0]<<endl;
return 0;}

结果为

1 2 1 2
1 2 2 1

指针 swap,但是内存没有换,这样是 \(O(1)\) 的。

写滚动数组时最好用这种方式。

4

那有的人就要慌了,swap 的复杂度就这么高吗。

#define N 10000000
vector<int> a,b;
signed main(){ios::sync_with_stdio(false),cin.tie(nullptr);
	a.resize(N);
	b.resize(N);
	fill(a.begin(),a.end(),1);
	fill(b.begin(),b.end(),2);
	For(i,1,N) swap(a,b);
return 0;}

结果不会 TLE。

vector 是 \(O(1)\) 交换指针。

5

#define N 1000000
set<int> a,b;
signed main(){ios::sync_with_stdio(false),cin.tie(nullptr);
	For(i,1,N) a.insert(i);
	For(i,1,N) b.insert(-i);
	For(i,1,N) swap(a,b);
return 0;}

结果不会 TLE。

其他 STL 也是 \(O(1)\) 交换指针。

posted @ 2022-09-12 14:20  ShaoJia  阅读(787)  评论(0编辑  收藏  举报