c++函数传值声明中出现&

来源:百度知道 编辑:UC知道 时间:2024/06/14 02:05:21
网上找的快排:
#include <iostream>
#include <stdlib.h>//交换两变量值
using namespace std;
void swap(int &a,int &b)
{
int c;
c=a;a=b;b=c;
} //将数组分成两部分,前一部分的值均比后一部分值小
//返回分界点
int Partition(int data[],int low,int high)
{
int pivokey;
pivokey=data[low];
while(low<high)
{
while(low<high&&data[high]>=pivokey)
high--;
swap(data[low],data[high]); while(low<high&&data[low]<=pivokey)
low++;
swap(data[low],data[high]);
}
return low;
}
刚开始的void swap(int &a,int &b)
中为什么会出现&??那个data[low]不应该是值吗?

swap(int &a,int &b)
swap(int a,int b)
两个语句功能是一样的,但在数据操作上不一样,swap(int &a,int &b)是对原值的引用,swap(int a,int b)会产生参数的副本,在数据量大的时候swap(int a,int b)会耗用更多的时间,详细情况请参考有关引用的资料。

这里&是引用,不是取地址
引用相当实参的别名,指的是实参,这里这样用相当直接对实参交换

这里&是引用,不是取地址
引用相当实参的别名,指的是实参,这里这样用相当直接对实参交换