Showing vectors

I have the following code, which works good, it is just for showing each element of a vector.

1
2
3
4
5
6
7
  void show_vector_char(vector<char> v)
{
	cout << "VECTOR: [";
	for (int i = 0;i < v.size();i++)
		cout << v[i] << " ";
	cout << "]" << endl;
}


I've been told that I should pass the parameters by reference, but I don't understand what does it change? Since I don't want to alter the content of the vector, but just showing it.

 
void show_vector_char(vector<char>& v)
As your code is, it makes a copy of the vector. If the vector is large, the copy can be expensive. Most likely you have been told to pass by const-reference, not just by reference. Passing by const-reference prevents you from changing the vector and it also eliminates the expensive copy.
> I've been told that I should pass the parameters by reference,
> but I don't understand what does it change?

In this case, by reference to const.

If the compiler can see the implementation of the function, it does not change anything.

Otherwise, pass by value would require that a copy of the vector be made.


This thread may be of interest http://www.cplusplus.com/forum/general/78138/
Topic archived. No new replies allowed.