C++来自特定数组的随机数生成器

Fun*_*nky 3 c++ arrays random

我希望能够从我将要放置的特定数组中生成随机数.例如:我想从数组{2,6,4,8,5}生成一个随机数.它只是我想要生成的数组中没有模式.

我只能使用视频教程https://www.youtube.com/watch?v=P7kCXepUbZ0&list=PL9156F5253BE624A5&index=16中的 srand()搜索如何从1-100生成随机数,但我不知道如何指定它将搜索的数组..

顺便说一句,我的代码与此相似..

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(int argc, char*argv[])
{
    srand(time(0)); 

    int i =rand()%100+1;
    cout << i << endl; 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Cpp*_*ris 5

这是一种现代的C++方法:

#include <array>
#include <random>
#include <iostream>

auto main() -> int
{
    std::array<int, 10> random_numbers = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 };

    std::random_device random_device;
    std::mt19937 engine(random_device());
    std::uniform_int_distribution<int> distribution(0, random_numbers.size() - 1);

    const auto random_number = random_numbers[distribution(engine)];
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读标准库中有关C++随机函数的更多信息:http://www.cplusplus.com/reference/random/