前端开发入门到精通的在线学习网站

网站首页 > 资源文章 正文

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

qiguaw 2024-10-28 17:27:17 资源文章 20 ℃ 0 评论

函数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 variables
    swap(a, b);
    cout << "Value of a now: "<< a << endl;
    cout << "Value of b now: "<< b << endl;
    return 0;
}

输出:

Value of a before: 10

Value of b before: 20

Value of a now: 20

Value 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: ABCD

Value of b before: function

Value of a now: function

Value of b now: ABCD

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

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

编程学习书籍分享:

编程学习视频分享:

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

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

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表