Search code examples
c++stl-algorithm

Why does the STL reverse algorithm not work as I expect?


Try to reverse a part of a vector:

vector<int> nums{1,2,3};
std::reverse(nums.begin(), nums.end()); //LINE1
std::reverse(nums.begin(), (nums.begin() + 1)); //LINE2
std::reverse((nums.begin() + 2), nums.end()); //LINE3

After LINE1, nums{3,2,1}

After LINE2 and LINE3, no change.

Expected: nums{2,3,1}


Solution

  • From the documentation for std::reverse:

    Reverse range

    Reverses the order of the elements in the range [first,last).

    Note the half-open range.

    So, assuming you have three elements (range [0;2]):

    1) std::reverse(nums.begin(), (nums.begin() + 1));

    This operates on range [0; 0+1) -> [0; 1) -> [0;0] (it's an open range, so the closing boundary is not included itself).

    2) std::reverse((nums.begin() + 2), nums.end());

    Here, you got it wrong anyway, regarding ranges reverse operate on. begin() + 2 means last element in your case, while end() is... end. So this line is meaningless and does nothing.