Search code examples
c++stdvector

Can you "swap" slices of C++ std vectors?


If I have two C++ vectors:

vector<int> a(5) {1,2,3,4,5};
vector<int> b(5) {6,7,8,9,10};

is there a one-line way to use the swap method to swap slices of a and b? Something like

swap(a[something ... something], b[something ... something]);

giving, for instance

a equal to {1,9,10,4,5} and b equal to {6,7,8,2,3}?


Solution

  • std::swap_ranges.

    std::swap_ranges(a.begin()+1, a.begin()+3, b.begin()+3);
    

    Demo