C/C++编程笔记:C++中的 swap 内置函数,用法详解

751 阅读1分钟

函数**std :: swap()**是C ++标准模板库(STL)中的内置函数,该函数交换两个变量的值。

句法:

swap(a,b)

**参数:**该函数接受两个必须交换的必需参数a和b。参数可以是任何数据类型。

**返回值:**该函数不返回任何内容,它交换两个变量的值。

下面的程序说明了swap()函数:

示例一:

#include <bits/stdc++.h>using namespace std;int main(){int a = 10;int b = 20;cout << "Value of a before: "<< a << endl;cout << "Value of b before: "<< b << endl;// swap values of the variablesswap(a, b);cout << "Value of a now: "<< a << endl;cout << "Value of b now: "<< b << endl;return 0;}

输出:

Value of a before: 10Value of b before: 20Value of a now: 20Value of b now: 10

示例二:

#include <bits/stdc++.h>using namespace std;int main(){string a = "ABCD";string b = "function";cout << "Value of a before: "<< a << endl;cout << "Value of b before: "<< b << endl;swap(a, b);cout << "Value of a now: "<< a << endl;cout << "Value of b now: "<< b << endl;return 0;}

输出:

Value of a before: ABCDValue of b before: functionValue of a now: functionValue of b now: ABCD

每天学点小知识,希望对你有帮助~

**另外如果你想更好的提升你的编程能力,学好C语言C++编程!**弯道超车,快人一步!笔者这里或许可以帮到你~

C语言C++编程学习交流圈子,QQ群464501141】微信公众号:C语言编程学习基地

分享(源码、项目实战视频、项目笔记,基础入门教程)

欢迎转行和学习编程的伙伴,利用更多的资料学习成长比自己琢磨更快哦!