To shuffle a vector in C++, you can use the `shuffle` function from the `
In this example,
intVector
containing integers.<vector>
for vectors and <algorithm>
for the shuffle
function.shuffle
function along with a random number generator to shuffle the elements of the vector.#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
int main() {
std::vector<int> intVector = {1, 2, 3, 4, 5};
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(intVector.begin(), intVector.end(), g);
for (int i : intVector) {
std::cout << i << " ";
}
return 0;
}
Output varies due to randomness.
In this example,
charVector
containing characters.<vector>
for vectors and <algorithm>
for the shuffle
function.shuffle
function along with a random number generator to shuffle the elements of the vector.#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
int main() {
std::vector<char> charVector = {'a', 'b', 'c', 'd', 'e'};
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(charVector.begin(), charVector.end(), g);
for (char c : charVector) {
std::cout << c << " ";
}
return 0;
}
Output varies due to randomness.
In this tutorial, we learned How to Shuffle a Vector in C++ language with well detailed examples.