Home > Mobile >  Reversing a vector using recursion in C
Reversing a vector using recursion in C

Time:10-03

I'm using the below code to reverse a vector (modify it).

void revArr(int i, vector<int> arr) {
    int n = arr.size();
    if (i >= n / 2) return;
    swap(arr[i], arr[n-i-1]);
    revArr(i   1, arr);
}

int main() {
    vector<int> arr = {2, 13, 5, 26, 87, 65, 73};
    revArr(0, arr);
    for (auto i: arr) {
        cout << i << " ";
    }
    cout << "" << endl;
    return 0;
}

Upon execution, I'm getting unchanged vector back on console:
2 13 5 26 87 65 73
Why is the vector not reversed?
Thanks in advance.

CodePudding user response:

As pointed out by richard-critten you are passing a copy of the vector to revArr this copy is reversed not the original arr If you want the function to modify the value passed to it you have two options: Pass by reference or pass by pointer. It will be up to you to decide which is more appropriate for your use case but given your example i think you want pass by reference. Very helpful table here to help you understand which to use and why: https://www.modernescpp.com/index.php/c-core-guidelines-how-to-pass-function-parameters

  • Related