Function reference parameter

Function reference parameter

Example 1: exchange data

#include<iostream>
using namespace std;
void swap(int &v1,int &v2)
{
	int temp;
	temp = v2;
	v2 = v1;
	v1 = temp;
}
int main()
{
	int a = 1;
	int b = 2;
	swap(a,b);
	cout << a << ',' << b << endl; 
	return 0;	
}

Example 2: string reference

#include<iostream>
using namespace std;
string::size_type find_char(string s,char c)
{
	string::size_type i = 0;
	while(i != s.size()&&s[i] != c)
		++i;
	return i;
}
int main()
{
	string s("Hello ASIA");
	
	cout << find_char(s,'o') << endl; 
	return 0;	
}
In the above example, although it is correct, there are two disadvantages. First, if the string is too long, it will slow down the running time of the program, which is uncomfortable. The solution is to use "reference" as a parameter. Second, if you write like this in find_char("Hello ASIA",'0 ') on the basis of solving the first problem, an error will be reported and the modification is very simple. That is to change the parameter to const type, as follows:
#include<iostream>
using namespace std;
string::size_type find_char(const string &s,char c)
{
	string::size_type i = 0;
	while(i != s.size()&&s[i] != c)
		++i;
	return i;
}
int main()
{
	string s("Hello ASIA");
	
	cout << find_char("Hello ASIA",'o') << endl; 
	return 0;	
}

Example 3: pointer reference

#include<iostream>
using namespace std;
void swap(int *&v1,int *&v2)
{
	int *temp = v1;
	v1 = v2;
	v2 = temp;
}
int main()
{
	int a = 1;
	int b = 2;
	int *pa = &a;
	int *pb = &b;
	cout<< "Before exchange" << endl; 
	cout << "a:" << a << " , b:" << b << endl; 
	cout << "*pa:" << *pa << " , *pb:" << *pb << endl;
	swap(pa,pb);//It's just that the pointer points are swapped, and the values of a and B don't change 
	cout<< "After exchange" << endl; 
	cout << "a:" << a << " , b:" << b << endl; 
	cout << "*pa:" << *pa << " , *pb:" << *pb << endl;
	return 0;	
}

But to exchange the values of a and B, there is only one way to change them, as follows

swap(*pa,*pb);

Posted on Thu, 30 Apr 2020 05:22:56 -0700 by nykoelle