In C++, you can shuffle an array using the Fisher-Yates shuffle algorithm.
In this example,
intArray
containing integers.intArray
.#include <iostream>
#include <algorithm>
#include <random>
#include <chrono>
int main() {
int intArray[] = {1, 2, 3, 4, 5};
int n = sizeof(intArray) / sizeof(int);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::shuffle(intArray, intArray + n, std::default_random_engine(seed));
std::cout << "Shuffled Array: ";
for (int i = 0; i < n; i++) {
std::cout << intArray[i] << " ";
}
return 0;
}
Shuffled Array: 4 2 1 5 3
In this example,
strArray
containing strings.strArray
.#include <iostream>
#include <algorithm>
#include <random>
#include <chrono>
int main() {
std::string strArray[] = {"apple", "banana", "cherry"};
int n = sizeof(strArray) / sizeof(strArray[0]);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::shuffle(strArray, strArray + n, std::default_random_engine(seed));
std::cout << "Shuffled Array: ";
for (int i = 0; i < n; i++) {
std::cout << strArray[i] << " ";
}
return 0;
}
Shuffled Array: banana cherry apple
In this tutorial, we learned How to Shuffle an Array in C++ language with well detailed examples.