【问题标题】:C++ & Qt: Random string from an array areaC++ 和 Qt:来自数组区域的随机字符串
【发布时间】:2015-09-08 02:32:24
【问题描述】:

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

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

#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 数组,但在这种情况下,我不知道如何将它用于随机字符串。

除此之外,可以从数组内的一个区域中选择一个随机字符串吗?例如,我只想要一个从 Mario 到 Yoshi 的随机字符串,这样 Pac Man 和 Sonic 就不能出现?

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

【问题讨论】:

  • C++ 标准现在不鼓励在 C++ 代码中使用 rand/srand。它与您的问题并不完全相关,但请考虑使用 标头
  • 或者在 Qt 应用程序中使用 qrand()。

标签: c++ arrays string qt random


【解决方案1】:

您应该使用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)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多