Shifting a vector in C++20

Viewed 724

I'd like to use this new feature from C++20 of shifting a vector to the right std::shift_right.

Something that I'm not sure about is how can I get the last element to the beginning of the vector after shifting?

Like in the example above... Where I'm saving the last element in a temp variable and then after shifting I set the first element to be the temp variable.

#include <iostream>
#include <vector>
#include <algorithm>



int main()
{
    std::vector<int> seq = { 5, 4, 3, 2, 1 };

    std::vector<int>::iterator it;
    std::vector<int>::iterator temp;
    temp = seq.end() - 1;


    std::shift_right(seq.begin(), seq.end(), 1);
    std::replace(seq.begin(), seq.end(), seq.at(0), *temp);

    for (it = seq.begin(); it != seq.end(); it = std::next(it))
        std::cout << *it << " ";

    return 0;
}
1 Answers

While you can probably achieve what you want with std::shift_right, the appropriate algorithm to do what you've described is std::rotate, which you can use without c++20 as well:

std::rotate(seq.begin(), seq.end() - 1, seq.end());    

Here's a demo.

The reason the shift_right version doesn't work is that you have an iterator to the last element. When you finish shifting, the original last element is overwritten, and the iterator now points to the shifted element instead. So what you can do is make a copy of the last element and then put that at the beginning:

int temp = seq.back();
std::shift_right(seq.begin(), seq.end(), 1);
seq[0] = temp;

Here's a demo. But note that this is a hack; use shift_right if you don't care about those elements that you are overwriting. If you care about the elements, then rotate the range.

Related