Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between function(vector<int> v) and function(vector<int>& v)? [duplicate]

While trying to perform insertion sort using vectors in C++, I discovered that when I used, it didn't perform the function:

void ins_sort(vector<int> v){
    //function body
}

Whereas when I did the following, it worked:

void ins_sort(vector<int>& v){
    //function body
}

Can someone please explain why?

like image 462
Mohit Sudhakar Avatar asked Oct 20 '25 01:10

Mohit Sudhakar


2 Answers

The & lets you pass parameters by reference. That is, you can modify them in the body of the function and still see them modified after you've called the function.

Without the &, you're passing a parameter by value. That is, the vector will be copied and you'll work with a copy of the vector while inside the function. After the function ends, you'll work again with the original vector.

like image 63
Blito Avatar answered Oct 21 '25 14:10

Blito


Basically passing by reference (&) passes the same vector, while passing by value (no-&) passes a copy of the vector. If the vector contains a lot of items, then there is a significant performance difference between the two. In addition, if the point is doing an insertion-sort, you probably want to sort the same vector, rather than a copy (unless you plan to return the copy, which will incur yet another performance hit).

like image 40
sircodesalot Avatar answered Oct 21 '25 13:10

sircodesalot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!