c++swap

logic fault with reversing the order of vector elements using std::swap


i have an exercise on chapter 8 of programming principles and practice by Strostrup ,it asks to write function that uses std::swap to reverse the elements of vector<int> here's my code

void rev_vect(vector<int>& v) {
    for (int i = 0; i < v.size(); i++)
            swap(v[i], v[v.size() - 1- i]);
}

the problem is that this function doesn't reverse the elements and the vectors passed to it remain the same, i have tried to see if there is something wrong with my function but unfortunately i wasn't able to find anything suspicious!, please help me to see what's wrong with the function i apologize if my question lacking formality as i'm new to programming.

i know that the vector subscript operator returns a reference to the vector elements and std::swap() swaps the values of it's arguments so i thought my logic should be correct.


Solution

  • Since you pass though all the container, you swap elements twice which brings them to the initial state.

    The correct code would be:

    void rev_vect(std::vector<int>& v) {
        for (int i = 0; i < v.size()/2; i++)
            std::swap(v[i], v[v.size() - 1- i]);
    }
    

    See the demo