【问题标题】:c++ Do-While, Random Words From Array For String With No Repititionc ++ Do-While,来自数组的随机单词,用于字符串而不重复
【发布时间】:2015-02-22 15:52:31
【问题描述】:

我想要做的是有一个单词数组,然后从数组中为字符串分配一个随机单词,但没有字符串可以包含相同的单词。我试过这个,但是当它运行时,它只会做一次do-while然后继续下一个do-while留下重复。那么我写的哪一部分是不正确的,我能做些什么来解决它?

string1 = words[rand()%110];

    do{
        string2 = words[rand()%110];
    }while (string == string1);

    do{
        string3 = words[rand()%110];
    }while (string3 == string1 && string3 == string2);

【问题讨论】:

  • 您的文字几乎无法理解,但您似乎在说程序在到达第二个循环之前处于不良状态。在这种情况下,我想知道您为什么发布第二个循环,带有你似乎并不关心的明显错误。
  • 你打算写“string2”而不是“string”吗?如果“字符串”实际上是变量的名称,则该循环将运行一次或永远运行。

标签: c++ random do-while


【解决方案1】:

第一个循环看起来不错。也许你需要在第二个循环中写|| 而不是&&

PS : 在第一个循环中,是while (string2 == string1); 而不是while (string == string1); ??

【讨论】:

  • 写作 ||而不是 && 工作。当问这个问题时,我重新编写了代码并写了字符串而不是 string2
【解决方案2】:
std::string getWord(std::vector<std::string> & words, size_t & unusedCount)
{
    size_t index = rand() % unusedCount;
    --unusedCount;
    std::swap(words[index], words[unusedCount]);
    return words[unusedCount];
}

std::vector<std::string> words;
// fill in words here
// ...
size_t wordsCount = words.size();
std::string string1 = getWord(word, wordsCount);
std::string string2 = getWord(word, wordsCount);
std::string string3 = getWord(word, wordsCount);

【讨论】:

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