Passing vector to a function in C++ 传递vector到函数

When we pass an array to a function, a pointer is actually passed. 

When a vector is passed to a function, a copy of the vector is created. For example, we can see below program, changes made inside the function are not reflected outside because function has a copy. 当传递vector到一个函数时,复制了这个vector的副本,函数里vector的改变不影响外面的vector,因为函数有一个副本。

// C++ program to demonstrate that when vectors 
// are passed to functions without &, a copy is 
// created. 
#include<bits/stdc++.h> 
using namespace std; 

// The vect here is a copy of vect in main() 
void func(vector<int> vect) 
{ 
vect.push_back(30); 
} 

int main() 
{ 
	vector<int> vect; 
	vect.push_back(10); 
	vect.push_back(20); 

	func(vect); 

	// vect remains unchanged after function 
	// call 
	for (int i=0; i<vect.size(); i++) 
	cout << vect[i] << " "; 

	return 0; 
} 

Output:

10 20

The above style of passing might also take a lot of time in cases of large vectors. So it is a good idea to pass by reference.上面这种传递方式耗费时间长,好想法是传递引用。

// C++ program to demonstrate how vectors 
// can be passed by reference. 
#include<bits/stdc++.h> 
using namespace std; 

// The vect is passed by reference and changes 
// made here reflect in main() 
void func(vector<int> &vect) 
{ 
vect.push_back(30); 
} 

int main() 
{ 
	vector<int> vect; 
	vect.push_back(10); 
	vect.push_back(20); 

	func(vect); 

	for (int i=0; i<vect.size(); i++) 
	cout << vect[i] << " "; 

	return 0; 
} 

Output:

10 20 30

If we do not want a function to modify a vector, we can pass it as a const reference.如果不想函数修改vector,最好是传递常量引用。

// C++ program to demonstrate how vectors 
// can be passed by reference with modifications 
// restricted. 
#include<bits/stdc++.h> 
using namespace std; 

// The vect is passed by constant reference 
// and cannot be changed by this function. 
void func(const vector<int> &vect) 
{ 
	// vect.push_back(30); // Uncommenting this line would 
							// below error 
	// "prog.cpp: In function 'void func(const std::vector<int>&)': 
	// prog.cpp:9:18: error: passing 'const std::vector<int>' 
	// as 'this' argument discards qualifiers [-fpermissive]" 
	
	for (int i=0; i<vect.size(); i++) 
	cout << vect[i] << " "; 
} 

int main() 
{ 
	vector<int> vect; 
	vect.push_back(10); 
	vect.push_back(20); 

	func(vect); 
	
	return 0; 
} 

Output:

10 20 

This article is contributed by Kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Recommended Posts:

猜你喜欢

转载自blog.csdn.net/qq_27009517/article/details/86504388