我需要int i[2]使用void swap(int& x)函数交换格式中的几个整数.如您所见,该函数采用类型的参数int&.这是函数的非工作版本:
int i[2] = {3, 7};
void swap (int& x)
{
int temp;
temp = x[1];
x[1] = x[0];
x[0] = temp;
}
int main()
{
cout << i[0] << ", " << i[1] << "\n"; // return the original: (3, 7)
swap(i);
cout << i[0] << ", " << i[1] << "\n"; // return i swapped: (7, 3)
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
编辑:答案不能使用任何其他功能参数.它必须使用一个int&参数.这是Bjarne Stroustrup的书中的一个问题:"C++编程语言",第三版.问题#4来自第5章.问题首先要求编写一个带有int*as参数的函数,而不是修改它以接受int&as参数.
引用不是指针.如果可以,我建议更改功能签名,但如果你坚持使用它,你可以做以下事情:
int *xx = &x;
int temp = xx[1];
xx[1] = xx[0];
xx[0] = temp;
Run Code Online (Sandbox Code Playgroud)
也就是说,您应该只使用std :: swap.