【问题标题】:Random string from vector C++ [closed]来自向量 C++ 的随机字符串 [关闭]
【发布时间】:2021-12-01 04:05:00
【问题描述】:

我对此代码有疑问。我得到了我所期望的结果,但我不明白为什么有时会得到结果,有时却没有。

在这种情况下,每次我运行代码时输出都会显示“潜水”这个词,但有时输出没有给我任何价值。

是因为if语句吗?我怎样才能总是得到结果(“潜水”)而不是有时?

#include <iostream>
#include <string>
#include <vector>
#include <ctime>
using namespace std;

int main()
{
    srand(time(NULL));

    vector <string> Words = {"dive", "friends", "laptop"};

    string n_words = Words[rand() % Words.size()];

    for(int i = 0; i < 1; i++)
    {
        if(n_words.length() <= 4)
        {
            cout << n_words << endl;
        }
    }    
}

编辑另一个例子:

我想从长度不同的单词列表中随机选择一个不超过 4 个字母的单词。当我运行我的代码时,有时我得到“潜水”,有时是“乐高”,有时什么也没有。有什么办法总能得到这两个值中的一些?

#include <iostream>
#include <string>
#include <vector>
#include <ctime>
using namespace std;

int main()
{
    srand(time(NULL));

    vector <string> Words = {"dive", "table", "laptop", "lego", "friends"}

    string n_words = Words[rand() % Words.size()];

    for(int i = 0; i < 1; i++)
    {
        if(n_words.length() <= 4)
        {
            cout << n_words << endl;
        }
    }    
}

【问题讨论】:

  • for(int i = 0; i &lt; 1; i++) -- 循环只迭代一次,因此您只有一次机会获得“潜水”一词。为什么您希望每次运行程序时都会出现dive
  • 这只是一个简单的逻辑,n_words 可以是"dive", "friends", "laptop" 中的任何字符串,因为for (int i = 0; i &lt; 1; i++) 只迭代一次,你只需要关心内部的 if 语句。并且只有一个长度小于等于4的字符串,即"dive"。在其他情况下将没有输出。
  • 如果你总是想要相同的答案,你需要播种相同的种子,而不是基于时间。
  • @GasparBonari -- 遵循代码的逻辑。如果n_words 原来是“朋友”怎么办?你得到了“朋友”这个词,而不是“潜水”。也许你相信rand() % Words.size() 总是等于 0?你认为rand() 的目的是什么?另外,如果随机性没有发生,程序不是绝对没用吗?
  • @GasparBonari 老实说,我真的不明白你想要达到什么目标。你有rand(),但出于某种原因,你不想要随机性——而是希望输出始终相同。

标签: c++ vector


【解决方案1】:

我个人会复制到一个辅助临时向量,对其进行洗牌,然后获取该向量的第一个元素。

我会把它放在一个单独的函数中。

在代码中可能是这样的:

std::string select_random_short_word(std::vector<std::string> const& long_words)
{
    // Create a vector and copy all "short" words to it
    std::vector<std::string> short_words;
    std::copy_if(begin(long_words), end(long_words), std::back_inserter(short_words),
                 [](std::string const& w) { return w.length() <= 4; });

    // Make sure there are any short words
    if (short_words.size() == 0)
    {
        return "";  // Nope, no short words
    }

    // Randomly shuffle the short words
    std::random_device device;
    std::default_random_engine engine(device());
    std::shuffle(begin(short_words), end(short_words), engine);

    // Return a random short word
    return short_words[0];
}

这会将您的 main 函数简化为:

int main()
{
    std::vector<std::string> words = {"dive", "table", "laptop", "lego", "friends"};
    std::cout << select_random_short_word(words) << '\n';
}

【讨论】:

  • 顺便说一句,可以修改代码以允许将短字的长度截止值作为参数传递,而不是使用固定的4
  • @drescherjm 我宁愿允许用户传递任何 lambda 来定义单词的要求。或者可能重载长度(默认4)和通用lambda? :)
猜你喜欢
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 2018-10-19
相关资源
最近更新 更多