几种交换两个数函数(swap函数)的写法和解析

#include <iostream>
using namespace std; /*值传递,局部变量a和b的值确实在调用swap0时变化了,当结束时,他们绳命周期结束*/
void swap0(int a, int b)
{
int tem = a;
a = b;
b = a;
} /*没有初始化指针就开始用,该函数是有问题的*/
void swap1(int *a, int *b)
{
int *tem; /*注意tem没有分配内存*/ *tem = *a;
*a = *b;
*b = *tem;
} /*函数内只是指针的变化,指针的值没有变化*/
void swap2(int *a, int *b)
{
int *tem; tem = a;
a = b;
b = tem; } /*指针传递实现两个数的交换*/
void swap3(int *a, int *b)
{
int tem; tem = *a;
*a = *b;
*b = tem;
} /*指针传递实现两个数的交换*/
void swap4(int &a, int &b)
{
int tem; tem = a;
a = b;
b = tem;
} int main()
{
int num1 = 1;
int num2 = 2; //swap0(num1, num2); //swap1(&num1, &num2); //swap2(&num1, &num2); //swap3(&num1, &num2); swap4(num1, num2); cout << num1 << endl << num2 << endl;
return 0;
}
上一篇:Dynamics365 WebAPI ADFS token 获取


下一篇:TCPL学习毕节:第六章hash表