c++_primer_exercise_1728_1729_1730

本文介绍如何使用C++生成均匀分布的随机数,并通过一个具体示例演示了如何统计这些随机数出现的频率。文章包括了必要的代码实现及解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*************************************************
 * IDE: VS2010
 *************************************************/
#include 
using std::cin; using std::cout; using std::endl;

#include 
using std::vector;

#include 
using std::map;

#include 
using std::default_random_engine;
using std::uniform_int_distribution;

// returns a vector of 100 uniformly distributed random numbers
vector rand_vec(unsigned long seed, unsigned min_val, unsigned max_val)
{
	// because engines and distributions retain state, they usually should be
	// defined as static so that new numbers are generated on each call
	static default_random_engine e(seed);
	static uniform_int_distribution u(min_val, max_val);
	vector ret;
	for (unsigned i = 0; i != 100; ++i)
	{
		ret.push_back(u(e));
	}
	return ret;
}


int main()
{
	vector v(rand_vec(255, 0, 9));
	map num_count;

	// count
	for (vector::iterator it = v.begin(); 
		 it != v.end(); ++it)
	{
		++num_count[*it];
	}

	// print
	for (map::iterator it = num_count.begin();
		 it != num_count.end(); ++it)
	{
		cout << it->first << " occurs " << it->second
			 << ((it->second > 1) ? " times" : " time") << endl;
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值