CodingHowTo

Rotate and Shuffle: Quick Helpers for std::vector

Rotate and Shuffle: Quick Helpers for std::vector

Rotating Elements

Rotation involves moving the elements of a vector to the right by a specified number of positions. The last element becomes the first, and so on. Here's how you can implement a rotate function:


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

template <typename T>
void rotateRight(std::vector<T>& vec, size_t n) {
    if (vec.empty() || n % vec.size() == 0) return;
    std::rotate(vec.rbegin(), vec.rbegin() + n % vec.size(), vec.rend());
}

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    rotateRight(vec, 2);
    for (int num : vec) {
        std::cout << num << " ";
    }
    return 0;
}

    

Shuffling Elements

Shuffling involves rearranging the elements in a vector randomly. The C++ Standard Library provides a convenient function for this purpose, std::shuffle. Here's how you can use it:


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

template <typename T>
void shuffleVector(std::vector<T>& vec) {
    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(vec.begin(), vec.end(), g);
}

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    shuffleVector(vec);
    for (int num : vec) {
        std::cout << num << " ";
    }
    return 0;
}

    

Conclusion

Rotating and shuffling elements in a std::vector are useful operations that can be easily implemented using C++ Standard Library functions. By defining helper functions like those shown above, you can perform these operations concisely and efficiently. These techniques can enhance the functionality of your C++ programs, allowing for more dynamic and interactive data handling.