To shuffle a list in C++, you can use the std::shuffle
method provided by the C++ standard library.
In this example,
,
, and
.numbers
with integer values.std::default_random_engine
.std::shuffle
function with the iterators of the list and the random number generator.std::shuffle
function randomly rearranges the elements in the list.#include <algorithm>
#include <random>
#include <list>
#include <iostream>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
std::vector<int> vec(numbers.begin(), numbers.end());
std::random_device rd;
std::default_random_engine rng(rd());
std::shuffle(vec.begin(), vec.end(), rng);
numbers.assign(vec.begin(), vec.end());
std::cout << "Shuffled list: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Shuffled list: 3 1 5 4 2
In this example,
,
, and
.words
with string values.std::default_random_engine
.std::shuffle
function with the iterators of the list and the random number generator.std::shuffle
function randomly rearranges the elements in the list.#include <algorithm>
#include <random>
#include <list>
#include <string>
#include <iostream>
int main() {
std::list<std::string> words = {"apple", "banana", "cherry", "date", "elderberry"};
std::vector<std::string> vec(words.begin(), words.end());
std::random_device rd;
std::default_random_engine rng(rd());
std::shuffle(vec.begin(), vec.end(), rng);
words.assign(vec.begin(), vec.end());
std::cout << "Shuffled list: ";
for (const std::string& word : words) {
std::cout << word << " ";
}
std::cout << std::endl;
return 0;
}
Shuffled list: cherry elderberry apple banana date
In this tutorial, we learned How to Shuffle a List in C++ language with well detailed examples.