不重复的随机数生成器(cpp/c++)

1 c++ random function generator

我想创建一个生成数字但不重复的函数。如果生成了每个数字,则可以清空数组并重新开始。

这是我编写的代码,但它不起作用。代码中的注释对代码进行了一些解释。允许的最大数字是“howManyWords”。这用于显示存储在数组中的单词

我想这样使用它:array\[random()\]

#include <stdio.h>
#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;
//public scope
int howManyWords; // how many words you have enter

int random(){
    int random;
    int numbers[howManyWords];
    srand(time(0)); //changing the algorithm
    random = rand() % howManyWords;
    numbers[random] = random; // store the digit in the position in the array equal to the digit that is generated
    for(int i=0; i<howManyWords; i++){ // going through every element in the array
        if(numbers[i] == random){ // if the number is already generated, generate a different number
        random = rand() % howManyWords;
        }
    }
    return random;
}
Run Code Online (Sandbox Code Playgroud)

Cal*_*eth 6

您应该使用函数对象,而不是使用函数(该函数会丢弃每次调用时返回的数字的状态)。

struct random_t {
    random_t(int max) : values(max), current(max) {
        std::iota(values.begin(), values.end(), 0); 
    }

    template<typename URBG = std::random_device &>
    int operator()(URBG&& urbg = default_random) {
        if (current == values.size()) { 
            shuffle(std::forward<URBG>(urbg));
        } 
        return values[current++]; 
    }
private:
    template<typename URBG>
    void shuffle(URBG&& urbg) { 
        std::shuffle(values.begin(), values.end(), std::forward<URBG>(urbg));
        current = 0; 
    }

    std::vector<int> values;
    std::vector<int>::size_type current;
    static thread_local std::random_device default_random;
};
Run Code Online (Sandbox Code Playgroud)

现场观看