概述
这是我使用C ++ 11对Ates Goral的回答的改编。我在这里添加了lambda,但原理是您可以传递它,从而控制字符串包含的字符:
std::string random_string( size_t length )
{
auto randchar = []() -> char
{
const char charset[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
const size_t max_index = (sizeof(charset) - 1);
return charset[ rand() % max_index ];
};
std::string str(length,0);
std::generate_n( str.begin(), length, randchar );
return str;
}
这是将lambda传递给随机字符串函数的示例:http : //ideone.com/Ya8EKf
为什么要使用C ++ 11?
因为您可以针对感兴趣的字符集生成遵循特定概率分布(或分布组合)的字符串。
因为它内置了对非确定性随机数的支持
因为它支持unicode,所以您可以将其更改为国际化版本。
例如:
#include
#include
#include
#include //for std::function
#include //for std::generate_n
typedef std::vector char_array;
char_array charset()
{
//Change this to suit
return char_array(
{'0','1','2','3','4',
'5','6','7','8','9',
'A','B','C','D','E','F',
'G','H','I','J','K',
'L','M','N','O','P',
'Q','R','S','T','U',
'V','W','X','Y','Z',
'a','b','c','d','e','f',
'g','h','i','j','k',
'l','m','n','o','p',
'q','r','s','t','u',
'v','w','x','y','z'
});
};
// given a function that generates a random character,
// return a string of the requested length
std::string random_string( size_t length, std::function rand_char )
{
std::string str(length,0);
std::generate_n( str.begin(), length, rand_char );
return str;
}
int main()
{
//0) create the character set.
// yes, you can use an array here,
// but a function is cleaner and more flexible
const auto ch_set = charset();
//1) create a non-deterministic random number generator
std::default_random_engine rng(std::random_device{}());
//2) create a random number "shaper" that will give
// us uniformly distributed indices into the character set
std::uniform_int_distribution<> dist(0, ch_set.size()-1);
//3) create a function that ties them together, to get:
// a non-deterministic uniform distribution from the
// character set of your choice.
auto randchar = [ ch_set,&dist,&rng ](){return ch_set[ dist(rng) ];};
//4) set the length of the string you want and profit!
auto length = 5;
std::cout<
return 0;
}
最后
以上就是傻傻寒风为你收集整理的c语言随机函数产生字母,如何在C ++中创建随机的字母数字字符串?的全部内容,希望文章能够帮你解决c语言随机函数产生字母,如何在C ++中创建随机的字母数字字符串?所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复