soham
soham

Reputation: 1676

Why does the swap through pointer not work in vector in C++?

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?

Upvotes: 1

Views: 92

Answers (1)

Baum mit Augen
Baum mit Augen

Reputation: 50063

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

Upvotes: 3

Related Questions