Home >Backend Development >C++ >How Can I Efficiently Shuffle a std::vector in C ?

How Can I Efficiently Shuffle a std::vector in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-30 19:23:14328browse

How Can I Efficiently Shuffle a std::vector in C  ?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn