【问题标题】:C++ How to simply select three random words from a list [duplicate]C ++如何从列表中简单地选择三个随机单词[重复]
【发布时间】:2021-05-11 21:03:59
【问题描述】:

我正在使用 C++Builder 制作应用程序。当我点击一个按钮时,它应该生成三个单词。我将如何实现这一目标?

到目前为止,这是我的代码:

void __fastcall TForm1::onevClick(TObject *Sender)
{
    #include <iostream>
    #include <string>
    #include <cstdlib>
    #include <ctime>
    
    const string SndList[5] = { "Raid", "Moscow", "Express", "Express", "Garrison"};
    
    maps1 ->Text =
}

编辑会这样工作

void __fastcall TForm1::onevClick(TObject *Sender)
{

    char Snd[5] = {"Raid","Moscow","Express","Express","Garrison"};
    maps1 ->Text = shuffle(Snd.begin(), Snd.end(), 3);
}

我在 char 数组初始化程序中获得了多余的元素

【问题讨论】:

  • 这更容易,因为它不是std::list。在互联网上搜索“C++ 生成统一随机数”。生成三个介于 0 和数组长度之间的随机数。使用数字作为数组的索引。
  • 您在使用哪些 C++ 资源来声明在方法中使用 #include?通常的约定是将它们放在源文件或头文件的顶部。
  • 有帮助的:std::shuffle。然后洗牌后,打印出前三项。
  • Thomas 这些在顶部,我懒惰地将它们复制到其中,因此我也可以包含我的包含而不应对其他所有内容
  • 在构建示例时,尽你所能,使其成为真正具有代表性的示例。如果你不这样做,你就会冒着人们解决错误问题的风险。使用minimal reproducible example 作为灵感。

标签: c++


【解决方案1】:

使用&lt;cstdlib&gt;和&lt;ctime&gt;,可以使用std::rand()(也可以使用C++Builder自带的System::Random()函数),例如:

#include <cstdlib>
#include <ctime>
// or: #include <System.hpp>

__fastcall TForm1::TForm1(TComponent *Owner)
    : TForm(Owner)
{
    std::srand(std::time(0));
    // or: System::Randomize();
}   

void __fastcall TForm1::onevClick(TObject *Sender)
{
    System::String SndList[5] = { "Raid", "Moscow", "Express", "Express", "Garrison"};
    int count = 5;

    System::String words[3];

    for(int i = 0; i < 3; ++i)
    {
        int index = std::rand() % count;
        // or: int index = System::Random(count);

        words[i] = SndList[index];

        for(int j = index + 1; j < count; ++j) {
            SndList[j-1] = SndList[j];
        }

        --count;
    }

    // use words[] as needed...
}

或者,如果您使用的是 C++Builder 的 clang-based compilers 之一,那么您可以使用 C++11 中引入的 std::shuffle() 算法和 random-number generators,例如:

#include <random>
#include <algorithm>

void __fastcall TForm1::onevClick(TObject *Sender)
{
    System::String SndList[5] = { "Raid", "Moscow", "Express", "Express", "Garrison"};

    std::random_device rd;
    std::mt19937 gen(rd());

    std::shuffle(SndList, SndList+5, gen);

    System::String words[3] = { SndList[0], SndList[1], SndList[2] };

    // use words[] as needed...
}

【讨论】:

  • 但是有没有办法生成 3 个单词而不是一个单词
  • 显然,您只需调用所选随机函数 3 次而不是 1 次
  • 如何去做呢?我是编码新手
  • @Christopher 我已经更新了我的答案
  • @Remmy Lebeau 我如何将它附加到标签上?这段代码会重复这些单词吗?因为我不需要他们重复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 2016-12-24
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
相关资源
最近更新 更多