来自vector c++的随机字符串



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

在本例中,输出应该显示单词"dive"每次我运行代码,但有时输出没有给我任何值。

是因为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个字母的单词。当我运行代码时,有时会出现&;dive&;有时"lego"有时什么也没有。有没有办法总是得到这两个值中的某一个呢?

#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;
}
}    
}

我个人会复制到第二个临时向量,对其进行洗牌,并获得该向量的第一个元素。

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

在类似这样的代码中:

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';
}