Chapter 16: Problem 12
What STL algorithm randomly shuffles the elements in a container?
Short Answer
Expert verified
Answer: The STL algorithm used to randomly shuffle elements within a container is the `std::shuffle` function. A simple example of its usage is as follows:
```cpp
#include
#include
#include
#include
#include
int main() {
std::vector numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Initialize a random number generator with the current time as seed.
std::default_random_engine random_engine(std::time(0));
// Shuffle the elements within the container using std::shuffle.
std::shuffle(numbers.begin(), numbers.end(), random_engine);
// Print the shuffled elements.
for (const int& num : numbers) {
std::cout << num << " ";
}
return 0;
}
```
In this example, a vector of integers is initialized and then shuffled randomly using `std::shuffle`. The shuffled elements are then printed, demonstrating the randomness of their order.
Step by step solution
Key Concepts
These are the key concepts you need to understand to accurately answer the question.