4

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?

yizzlez
  • 8,757
  • 4
  • 29
  • 44

2 Answers2

10

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.

Blito
  • 328
  • 2
  • 9
2

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).

sircodesalot
  • 11,231
  • 8
  • 50
  • 83