最近遇到一个问题,需要通过一个函数返回多个值。无奈C,C++不能返回多个值。所以就想有什么方法可以解决。
网上方法比较杂乱,一般有两种替代做法:
1. 利用函数的副作用, 返回值在函数外定义, 在函数内修改, 一般为void函数。
例1.1输入x,y求修改后的x,y
1 #include<iostream> 2 using namespace std; 3 void swap(int *p,int *q) 4 { 5 int temp; 6 temp=*p; 7 *p=*q; 8 *q=temp; 9 } 10 int main() 11 { 12 int a,b; 13 cin>>a>>b; 14 cout<<"the num is :"<<a<<b<<endl; 15 swap(a,b);//swap(&a,&b); 16 cout<<"the sorted num is :"<<a<<b<<endl; 17 }