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++:
- Include the necessary headers:
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
- Create a vector:
std::vector<int> myVector = {1, 2, 3, 4, 5};
- Create a random number generator:
std::random_device rd;
std::mt19937 g(rd());
- 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.
- 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.