1

I have the following code:

using namespace std; template<class T> void myswap(T* a, T* b) { T temp = *a; *a = *b; *b = temp; } template<class T> void printArr(vector<T> arr) { cout << "[ "; for(int i = 0; i < arr.size(); i++) { cout << arr[i] << " "; } cout << "]"; } void sampleSwap(vector<int> arr) { //swapping first two element myswap(&arr[0], &arr[1]); printArr(arr); cout << endl; } int main() { srand(500); vector<int> arr; for(int i = 0; i < N; i++) { arr.push_back(rand() % LIMIT); } printArr(arr); cout << endl; sampleSwap(arr); printArr(arr); return 0; } 

I got the following output:

[ 398 57 417 270 271 918 903 314 569 70 ] [ 57 398 417 270 271 918 903 314 569 70 ] [ 398 57 417 270 271 918 903 314 569 70 ] 

I tried to swap the first and second elements of my vector. The vector content is changed in the function but it doesn't retain the change after the function exits. Am I missing something?

3
  • 4
    You take a copy of you vector in sampleSwap, use pass by reference: sampleSwap(vector<int>& arr) Commented Feb 7, 2015 at 23:45
  • Read about pass by value versus pass by reference. Commented Feb 7, 2015 at 23:46
  • Oh! Pretty silly. Thanks BTW. Commented Feb 7, 2015 at 23:47

1 Answer 1

3

You pass the vector by value to sampleSwap, so only a copy of the vector you have in the main gets modified. Pass by reference instead:

void sampleSwap(vector<int> &arr) ^ 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.