简单的 C++ 交换函数 [英] Simple C++ swap function

查看:61
本文介绍了简单的 C++ 交换函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我有一个这样的函数,用来交换两个数字,它不起作用[swap],(我知道我可以通过在原型中声明指针来做到这一点,然后传递函数的地址)main()) 中的各个变量,但适用于数组,无需传递指针和地址.

Why is it that if I have a function like this, to swap two numbers, it doesn't work[swap], (I know I can do this by declaring pointers in the prototype, and then pass the address of the respective variables in main()), but works for array, without having to pass pointers and addresses.

不起作用

void num_exchange(int m, int n);

int main(){

int num1 = 5;
int num2 = 6;

num_exchange(num1 , num2 );

cout << "num1 =" << num1 << endl;
cout << "num2 =" << num2 << endl;

return 0;
}

void num_exchange(int m, int n){
int temp;
temp = m;
m = n;
n = temp;
}

作品

void arr_exchange(int [], int);

int main(){


int n[7] = { 0, 0, 0, 0, 0, 0, 0 };

arr_exchange(n, 7);
for (int i = 0; i < 7; i++)
    cout << n[i] << " ";

return 0;
}

void arr_exchange(int x[], int){
for (int i = 0; i < 7; i++)
    x[i] = 1;
}

推荐答案

void num_exchange(int m, int n){
int temp;
temp = m;
m = n;
n = temp;
}

修改输入整数的副本.要使您的代码工作,请使用

modifies copies of the input integers. To make your code work use

void num_exchange(int& m, int& n){
int temp;
temp = m;
m = n;
n = temp;
}

代替(注意第一行中的 &).这称为通过引用传递.一般来说,使用 std::swap 来交换东西.

instead (note the & in the first line). This is called passing by reference. In general, use std::swap to swap things.

void arr_exchange(int x[], int){
for (int i = 0; i < 7; i++)
    x[i] = 1;
}

工作,因为在 C++

works because in C++

void arr_exchange(int x[], int){

相当于

void arr_exchange(int* x, int){

所以这里传递了一个指针,从而修改了原始数据.

So here a pointer is passed and thus the original data is modified.

这篇关于简单的 C++ 交换函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆