C++ & Qt : Random string from an array area

标签 c++ arrays string qt random

在我的小型 Qt 应用程序中,我想在单击按钮后从数组中选择一个随机字符串。我已经阅读了很多主题,但对我没有任何用处。

所以在我的插槽中有一个包含多个字符串的数组。我还实现了 <string>, <time.h>和沙兰德。

#include "smashrandom.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>

SmashRandom::SmashRandom(QWidget *parent)
    : QWidget(parent)
{
    // shortened version
    connect(button, SIGNAL(clicked()), this, SLOT(Randomizer()));
}

void SmashRandom::Randomizer()
{

    srand((unsigned int)time(NULL));

    std::string characters[6] = {"Mario", "Luigi", "Peach", "Yoshi", "Pac Man", "Sonic"};
}

但是如何从我的数组“字符”中随机选择一个字符串?通常我将 rand()% 用于 int 或 double 数组,但在这种情况下,我不知道如何将它用于随机字符串。

除此之外,可以从数组内部的区域中选择一个随机字符串吗?例如,我只想要一个从马里奥到耀西的随机字符串,这样吃 bean 人和索尼克就不会出现了?

我希望你能理解我的问题并提前致谢。 :)

最佳答案

你应该使用 random标题。

#include <random>

std::default_random_engine generator;
std::uniform_int_distribution dist(0, 5);
int StringIndex = dist(generator);

std::string ChosenString = characters[StringIndex];

上面的代码会在你的数组中生成一个随机索引。

如果要限制范围,更改dist的构造函数,例如(dist(0,2)只允许Mario、Luigi和Peach被选中,索引 0 1 和 2)。

关于C++ & Qt : Random string from an array area,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30983360/

相关文章:

arrays - 通过动态构造的变量名称间接分配给bash数组变量

PHP 修改数组

C - 比较函数 - 需要解释

javascript - .contains() 在循环时不接受数组元素作为参数

Java - 从字符串中获取名称

php - 在网站结构中找到 "orphan"文件

c++ - 什么时候用指针调用C++类构造函数?

c++ - gcov 没有生成所有 gcda 文件

c++ - 标记字符串并构建 multimap

c++ - 以类似方式访问数组中的结构成员 : padding in structs different than in arrays?