SoFunction
Updated on 2025-04-14

Summary of the use of std::shuffle in C++

Use of std::shuffle

std::shuffleis a function in the C++ standard library used to randomly arrange (shuffle) elements in containers. Its implementation is based on modern random number generators, so it is morestd::random_shuffleMore secure and flexible (std::random_shuffleRemove after C++14 is deprecated and removed after C++17).

1. Syntax

#include <algorithm>
#include <random>

std::shuffle(RandomIt first, RandomIt last, URBG&& g);
  • firstandlast: Indicates the range to be randomly disrupted ([first, last))。
  • g: Random number generator must comply with UniformRandomBitGenerator (such asstd::mt19937)。
  • Return value: None (the function will directly modify the content of the input range).

2. Use examples

#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;
#include <random> // Need to include the <random> header file
int main() {
    std::vector&lt;int&gt; vec = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    // Create a random number generator    std::random_device rd;  // Random device (hardware entropy source)    std::mt19937 g(rd());   // Mason's rotation algorithm (commonly used random number engine)
    // Chaotic order    std::shuffle((), (), g);

    // The result after the output is disrupted    std::cout &lt;&lt; "Shuffled vector: ";
    for (int num : vec) {
        std::cout &lt;&lt; num &lt;&lt; " ";
    }
    std::cout &lt;&lt; std::endl;

    return 0;
}

3. Code parsing

  • Create a random number generator

    • std::random_device rd;: Used to generate seeds.
    • std::mt19937 g(rd());: Use the Mason rotation algorithm (Mersenne Twister) as the pseudo-random number engine.
  • Callstd::shuffleReshuffle

    • std::shuffle((), (), g);RedisruptvecThe order of elements in  .
  • Print the messed array

    • Traversal and outputvec

4. Sample output

Shuffled vector: 3 7 5 9 1 4 2 8 6

(The order of output is random, and the results may be different for each run.)

5. Important Notes

Why notstd::random_shuffle

  • std::random_shuffleRequires internal callrand(), its randomness is weak, andrand()Not thread-safe.
  • std::shuffleAllows the use of high-quality random number generators (e.g.std::mt19937)。

std::mt19937 vs std::default_random_engine

  • std::default_random_engineIt may be different because different compilers implement differently, so it is recommended to usestd::mt19937

How to use fixed seeds for reproducible random shuffles?

std::mt19937 g(42);  // 42 as a fixed random seedstd::shuffle((), (), g);

This way, every time you run the code, you will get the same disruption result.

6. Applicable scenarios

  • Random sorting of data
  • Generate random test cases
  • Shrink (such as playing cards)
  • Scramble data to avoid sorting bias (such as machine learning data preprocessing)

7. Conclusion

std::shuffle is a random shuffle method recommended in modern C++. Combined with std::mt19937, it can provide high-quality randomness and is suitable for various randomly arranged scenarios.

🚀 It is recommended to use std::shuffle instead of std::random_shuffle, and pair it with std::mt19937 for better randomness and controllability!

This is the article about the use of std::shuffle in C++. For more related C++ std::shuffle content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!