C & C++

C & C++

Made by DeepSource

Found use of deprecated std::random_shuffle type CXX-W2032

Anti-pattern
Minor
Autofix

std::random_shuffle is deprecated because it uses an unspecified RNG (Random Number Generator) which can lead to unpredictable behavior. The iterator-only version of std::random_shuffle usually depends on std::rand, which is now also discussed for deprecation.

Instead of using std::random_shuffle, you should use std::shuffle which requires you to provide a function object that explicitly defines the behavior you want when generating random numbers. This API is deprecated in C++ 14 and removed in C++ 17.

Bad practice

#include <iostream>
#include <algorithm>
#include <vector>
#include <random>

int main() {
    std::vector<int> v{1, 2, 3, 4, 5};
    // deprecated since c++14, removed in C++17
    std::random_shuffle(v.begin(), v.end());

    for (auto i : v) {
        std::cout << i << " ";
    }
}

Recommended

#include <iostream>
#include <algorithm>
#include <vector>
#include <random>

int main() {
    std::vector<int> v{1, 2, 3, 4, 5};

    // obtain a time-based seed:
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

    std::shuffle(v.begin(), v.end(), std::default_random_engine(seed));

    for (auto i : v) {
        std::cout << i << " ";
    }
}