brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.9 KiB · c6dcd72 Raw
53 lines · plain
1.. title:: clang-tidy - modernize-replace-random-shuffle2 3modernize-replace-random-shuffle4================================5 6This check will find occurrences of ``std::random_shuffle`` and replace it with7``std::shuffle``. In C++17 ``std::random_shuffle`` will no longer be available8and thus we need to replace it.9 10Below are two examples of what kind of occurrences will be found and two11examples of what it will be replaced with.12 13.. code-block:: c++14 15  std::vector<int> v;16 17  // First example18  std::random_shuffle(vec.begin(), vec.end());19 20  // Second example21  std::random_shuffle(vec.begin(), vec.end(), randomFunc);22 23Both of these examples will be replaced with:24 25.. code-block:: c++26 27  std::shuffle(vec.begin(), vec.end(), std::mt19937(std::random_device()()));28 29The second example will also receive a warning that ``randomFunc`` is no longer30supported in the same way as before so if the user wants the same31functionality, the user will need to change the implementation of the32``randomFunc``.33 34One thing to be aware of here is that ``std::random_device`` is quite expensive35to initialize. So if you are using the code in a performance critical place,36you probably want to initialize it elsewhere.37 38Another thing is that the seeding quality of the suggested fix is quite poor:39``std::mt19937`` has an internal state of 624 32-bit integers, but is only40seeded with a single integer. So if you require41higher quality randomness, you should consider seeding better, for example:42 43.. code-block:: c++44 45  std::shuffle(v.begin(), v.end(), []() {46    std::mt19937::result_type seeds[std::mt19937::state_size];47    std::random_device device;48    std::uniform_int_distribution<typename std::mt19937::result_type> dist;49    std::generate(std::begin(seeds), std::end(seeds), [&] { return dist(device); });50    std::seed_seq seq(std::begin(seeds), std::end(seeds));51    return std::mt19937(seq);52  }());53