Reversing a vector using recursion in C++

  c++, recursion

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.

Source: Windows Questions C++

LEAVE A COMMENT