在我的小型 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/