Efficient Shuffling of a std::vector
When shuffling a std::vector, efficiency plays a crucial role. The provided method using an intermediate array and type-specific knowledge is not optimal.
Modern C Approach
In C 11 and later, a more efficient approach is available:
#include <algorithm> #include <random> auto rng = std::default_random_engine {}; std::shuffle(std::begin(cards_), std::end(cards_), rng);
This method utilizes the std::shuffle function, which efficiently randomizes the elements. Remember to reuse the rng instance across multiple std::shuffle calls for consistent randomization.
Personalized Shuffling
If you desire distinct randomized sequences across program executions, seed the random engine with the output of std::random_device:
auto rd = std::random_device {}; auto rng = std::default_random_engine { rd() }; std::shuffle(std::begin(cards_), std::end(cards_), rng);
C 98 Approach
For C 98, the std::random_shuffle function remains applicable:
#include <algorithm> std::random_shuffle(cards_.begin(), cards_.end());
The above is the detailed content of How Can I Efficiently Shuffle a std::vector in C ?. For more information, please follow other related articles on the PHP Chinese website!