Random array generation with no duplicates

前端 未结 9 954
無奈伤痛
無奈伤痛 2020-11-28 12:48

I am trying to create something that generates a random array with no duplicate values. I\'ve already looked at other answers but none seem to help me understand. I cannot t

9条回答
  •  失恋的感觉
    2020-11-28 13:13

    You start off filling a container with consecutive elements beginning at 0

    std::iota(begin(vec), end(vec), 0);

    then you get yourself a decent random number generator and seed it properly

    std::mt19937 rng(std::random_device{}());

    finally you shuffle the elements using the rng

    std::shuffle(begin(vec), end(vec), rng);

    live on coliru


    On some implementations random_device doesn’t work properly (most notably gcc on windows) and you have to use an alternative seed, i.e. the current time → chrono.

提交回复
热议问题