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

时间:2016-08-26 08:27:58

标签: 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;
}

3 个答案:

答案 0 :(得分: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)];
}

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

答案 1 :(得分:0)

为此数组生成随机索引:

在你做一个随机值之前,让我们初始化'系统':

srand((unsigned int)time(0)); // somewhere in the beginning of main, for example

然后你在某处初始化你的数组,让我们这样说:

std::vector<int> array;
fillOutArray(array);
你得到的第一条消息就是:{10,5,3,6}

现在你想从这个数组中获取一个随机值(在这些数据中包含10,5,3或6个):

auto index = rand() % (array.size());
auto yourValue = array[index];

就是这样。

答案 2 :(得分:0)

使用模数来改变输出范围可能会引入轻微的偏差。见this talk。如果这是您的问题,请考虑使用“随机”标准库,因为您使用的是c ++。

相关问题