swap(a,b)函数的应用

用一个函数实现2个变量值的交换:

#include<iostream>
#include<cstdio>
using namespace std;
int heap_size,n;
void swap(int &a,int &b)  //swap()作为独立函数,应用于交换。
{  int t=a;a=b;b=t; }

int main()
{   int x,y;
    cin>>x>>y;
    swap(x,y);
    cout<<x<<" "<<y;
    return 0;
}

使用stl中的交换函数swap( ),增加头文件 <algorithm>,也可完成交换。

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int heap_size,n;
int main()
{
    int x,y;
    cin>>x>>y;
    swap(x,y);
    cout<<x<<" "<<y;
    return 0;
}

 

posted on 2018-12-12 14:33  lcdxjsj  阅读(406)  评论(0编辑  收藏  举报

导航