你如何在 C++ 中生成随机字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2146792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you generate random strings in C++?
提问by Jichao
I am looking for methods to generate random strings in C++.Here is my code:
我正在寻找在 C++ 中生成随机字符串的方法。这是我的代码:
string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
srand(time(NULL));
for (int i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];
return result;
}
But the seed(time(NULL))
is not random enough.Are there any other better way to generate random strings in C++?
但是seed(time(NULL))
不够随机。在C++中还有其他更好的方法来生成随机字符串吗?
回答by sharptooth
Don't call srand()
on each function call - only call it once at first function call or program startup. You migh want to have a flag indicating whethersrand()
has already been called.
不要srand()
在每次函数调用时都调用——只在第一次函数调用或程序启动时调用一次。您可能需要一个标志来指示是否srand()
已经被调用。
The sugested method is good except that you misuse srand()
and get predictably bad results.
建议的方法很好,只是您会误用srand()
并得到可预见的糟糕结果。
回答by Chris Jester-Young
You can use Boost.Random. It uses a different generator than the one provided with most standard libraries, that should be more robust.
您可以使用Boost.Random。它使用与大多数标准库提供的生成器不同的生成器,这应该更健壮。
In specific, most standard libraries provide linear congruential generators, which don't perform very well when you mod
their results with small numbers. Boost.Random has a Mersenne twister generator.
具体来说,大多数标准库都提供线性同余生成器,当你mod
得到小数字的结果时,它们的性能不是很好。Boost.Random 有一个梅森扭曲发生器。
As sharptooth says, though (good spotting!), only seed the generator once, at the very start of your program. Seeding it every time you want something random is counter-productive.
正如sharptooth所说,虽然(很好的发现!),只在程序开始时为生成器播种一次。每次你想要随机的东西时都播种它会适得其反。
回答by Phong
Make an interface to get a random number in this site http://www.random.org/and you will be sure to get a real random number! But if you are looking for performance...
在本站http://www.random.org/制作一个获取随机数的界面,你一定会得到一个真正的随机数!但是,如果您正在寻找性能...
回答by doron
On unix systems you can read random values from the file /dev/random
在 unix 系统上,您可以从文件中读取随机值 /dev/random
回答by gred
If you prefer to use the standard library, then you can do something like this:
如果您更喜欢使用标准库,那么您可以执行以下操作:
<somewhere else>
srand(NULL);
</somewhere else>
char get_rand_char() {
static string charset(...);
return charset[rand() % charset.size()];
}
std::string generate_random_string(size_t n) {
char rbuf[n];
std::generate(rbuf, rbuf+n, &get_rand_char);
return std::string(rbuf, n);
}
This code is naturally more modular, and standard library maintainers tend to write better code than me. This way I can change the random character generating part of the code without touching anything else. I could even forward to a function that randomly picks a random number generator! Not that it would compound the randomness or anything...
这段代码自然更加模块化,标准库维护者往往会写出比我更好的代码。这样我就可以更改代码的随机字符生成部分,而无需触及任何其他内容。我什至可以转发一个随机选择随机数生成器的函数!并不是说它会增加随机性或任何东西......
回答by infoclogged
use std::generate_n. This way you can specify the length of your generated string. In the below case its 4.
使用 std::generate_n。通过这种方式,您可以指定生成的字符串的长度。在下面的情况下,它是 4。
std::string uniqueName() {
auto randchar = []() -> char
{
const char charset[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const size_t max_index = (sizeof(charset) - 1);
return charset[ rand() % max_index ];
};
std::string str(4,0);
std::generate_n( str.begin(), 4, randchar );
return str;
}