Home > Software design >  Rotate a vector in right direction using std::rotate()
Rotate a vector in right direction using std::rotate()

Time:06-06

How to rotate a vector in right direction by K steps using std::rotate? Is there a better or faster method to rotate a vector(array) than std::rotate?

CodePudding user response:

How to rotate a vector in right direction by K steps using std::rotate?

The second parameter to std::rotate is an iterator to the new first element after the rotation. So, to do a right rotate by 1 step, that would mean the end() - 1 should be the new first etc.

Generalized:

template<class... T>
void rotate_right(std::vector<T...>& v, std::size_t steps) {
    if(steps %= v.size())
        std::rotate(v.begin(), std::prev(v.end(), steps), v.end());
}

Is there a better or faster method to rotate a vector(array) than std::rotate?

No, I don't think there is. If you find it too slow, you could use the version that uses one of the parallel execution policies and see if that speeds it up. Example:

#include <execution>

template<class... T>
void rotate_right(std::vector<T...>& v, std::size_t steps) {
    if(steps %= v.size())
        std::rotate(std::execution::par, v.begin(), std::prev(v.end(), steps), v.end());
}
  • Related