shuffle vector c++

To shuffle a vector in C++, you can use the std::shuffle function from the <algorithm> library. Here are the steps to shuffle a vector in C++:

  1. Include the necessary headers:
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
  1. Create a vector:
std::vector<int> myVector = {1, 2, 3, 4, 5};
  1. Create a random number generator:
std::random_device rd;
std::mt19937 g(rd());
  1. Shuffle the vector using the std::shuffle function:
std::shuffle(myVector.begin(), myVector.end(), g);

The std::shuffle function takes three parameters: the beginning iterator of the vector, the ending iterator of the vector, and the random number generator.

  1. Output the shuffled vector:
for (const auto& element : myVector) {
    std::cout << element << " ";
}

This will print the shuffled vector.

That's it! The vector has been shuffled in C++ using the std::shuffle function.