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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With