函数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++编程!弯道超车,快人一步!笔者这里或许可以帮到你~

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

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

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

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/258a/p/14525878.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!