简单的C ++交换功能 [英] Simple C++ swap function

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

问题描述

为什么,如果我有这样的功能,交换两个数字,这是行不通的[交换],(我知道我可以在原型声明指针做到这一点,再通的地址在主各个变量()),但适用于阵列,而不必通过指针和地址。

不工作

 无效num_exchange(INT男,INT N);诠释主(){INT NUM1 = 5;
INT NUM2 = 6;num_exchange(NUM1,NUM2);COUT<< NUM1 =&所述;&下; NUM1<< ENDL;
COUT<< NUM2 =&所述;&下; NUM2<< ENDL;返回0;
}无效num_exchange(INT男,INT N){
INT温度;
TEMP =米;
M = N;
N =温度;
}

作品

 无效arr_exchange(INT [],int);在诠释主(){
INT N [7] = {0,0,0,0,0,0,0};arr_exchange(N,7);
的for(int i = 0;我7;;我++)
    COUT<< N [1] - ;&下; ;返回0;
}无效arr_exchange(INT X [],INT){
的for(int i = 0;我7;;我++)
    X [I] = 1;
}


解决方案

 无效num_exchange(INT男,INT N){
INT温度;
TEMP =米;
M = N;
N =温度;
}

输入整数

修改的拷贝的。为了使您的code工作中使用

 无效num_exchange(INT&安培;男,INT和放大器; N){
INT温度;
TEMP =米;
M = N;
N =温度;
}

代替(注意&放大器;第一行)。这就是所谓的通过引用传递的。一般情况下,使用的std ::互换交换的东西。

 无效arr_exchange(INT X [],INT){
的for(int i = 0;我7;;我++)
    X [I] = 1;
}

工作,因为在C ++

 无效arr_exchange(INT X [],INT){

等同于

 无效arr_exchange(INT * X,INT){

因此​​,这里的指针被传递,从而原始数据被修改

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.

Doesn't work

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;
}

Works

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;
}

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;
}

works because in C++

void arr_exchange(int x[], int){

is equivalent to

void arr_exchange(int* x, int){

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

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

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