【问题标题】:C++ Returning a random value from a subset of a VectorC++ 从向量的子集中返回一个随机值
【发布时间】:2017-04-22 20:45:31
【问题描述】:

有人可以帮我找出一种方法,从一个按顺序有 N 个值的向量返回一个值。并且返回值必须在集合的上半部分。

例如,

如果有一个包含以下整数的向量: {1, 2, 3. 4, 5, 6}

从 {4,5,6} 返回一个随机整数。我好难过!

最终目标是创建一个“加权骰子”,其中掷骰的值返回更高的值。我的解决方案是前面提到的向量的使用。

void LoadedDie::loadedRoll(int numberOfSides)
{

    vector<int> diceSides(numberOfSides+1); 


    for (int index = 1; index < numberOfSides+1; index ++)

    {
        diceSides[index]=index; 
    }



    for (int index=1; index < numberOfSides+1; index ++)

    {
        cout << diceSides[index]; 
    }
}

所以我此时已创建骰子,但无法弄清楚如何从向量的后半部分获取随机值。

【问题讨论】:

  • 这很具体。你首先尝试过/想过做什么?表明你付出了实际的努力。
  • 我已经创建了向量,但只需要有关如何在给定索引处开始搜索向量然后使用 rand() 获取值的指导。我是初学者,无法理解它。
  • 然后显示你的代码,有总比没有好......即使发布代码有点明显。

标签: c++ vector random integer


【解决方案1】:

您可以生成一个范围内的随机整数,并使用下标运算符来访问您的向量。

int max = yourVector.size()-1; //-1 to stay in range
int min = max/2;
int randIndex = min + (rand() % (int)(max - min + 1));
yourVector[randIndex]; // this is a random int in your vector

这有点偏颇,因此您可以将以下内容用于无根据的:

#include <random>

int max = yourVector.size()-1; //-1 to stay in range
int min = max/2;
std::random_device seed;     // initialise a seed once
std::mt19937 numberGen(seed()); 
std::uniform_int_distribution<int> gen(min,max); 

int randIndex = gen(numberGen);
yourVector[randIndex]; // this is a random int in your vector

编辑

按照建议,您可以在 std::vector 中使用 .at() 函数以确保安全:

yourVector.at(randIndex);

【讨论】:

  • 但是如果向量被改变,通过索引访问它可能是危险的。使用at( ) 访问它更安全。
  • 啊,这真的很有帮助。
  • @EvanCarslake:此代码已经使用了向量的实际大小,而不是硬编码 6 的长度。向量中的“更改”可能导致问题的唯一方法是调整它的大小,在调用size() 和使用分发之间,但中间没有对用户提供的代码的回调,因此这种更改只能发生在另一个线程上。无论您使用下标还是at(),竞争条件都是未定义的行为。
猜你喜欢
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多