c语言随机函数产生字母,如何在C ++中创建随机的字母数字字符串?

这是我使用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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值