从整数列表中选择一个随机数

Choose a random number from a list of integer

本文关键字:一个 随机数 整数 列表 选择      更新时间:2023-10-16

我有一个整数intList = {1, 3. 5. 2}列表(它只是一个例子整数和大小都是未知的)。我必须从列表中随机选择一个数字。

RandomInt = rand() % intList.size() 

的工作方式与 RandomInt = rand() % 4

相似

,生成1 ~ 4之间的随机数。而intList则不同。

如果我使用RandomInt = std::random_shuffle = (intList, intList.size())仍然出现错误。我不知道怎么从一个列表中选择一个随机数

作为子步骤,您需要生成随机数,因此您不妨使用c++ 11的方式(而不是使用modulo,顺便说一下,众所周知,它对小数字有轻微的偏见):

开头
#include <iostream>
#include <random>
#include <vector>
int main()
{
    const std::vector<int> intList{1, 3, 5, 2};

现在定义随机生成器:

    std::random_device rd; 
    std::mt19937 eng(rd());
    std::uniform_int_distribution<> distr(0, intList.size() - 1);

当您需要生成一个随机元素时,您可以这样做:

    intList[distr(eng)];
}

你只需要使用"indirection":

std::vector<int> list{6, 5, 0, 2};
int index = rand() % list.size(); // pick a random index
int value = list[index]; // a random value taken from that list
  int arrayNum[4] = {1, 3, 5, 2};
  int RandIndex = rand() % 5; // random between zero and four
  cout << arrayNum[RandIndex];