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 @   ShaoJia  阅读(1892)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
历史上的今天:
2021-09-12 概率期望题 切木棍
2021-09-12 std::sort 的注意事项
点击右上角即可分享
微信分享提示