我想将boost::random
数字生成器对象传递给函数。我已经编写了这个小程序来测试我是否做得正确:
#include <cstdlib>
#include <iostream>
#include <exception>
#include <boost/random.hpp>
#include <boost/random/random_device.hpp>
// ---------- function declarations ----------
void print_random_num(boost::random::uniform_int_distribution<unsigned long> &gen, boost::random::mt19937 &rng);
// ---------- main ----------
int main()
{
try
{
boost::random::random_device seeder;
boost::random::mt19937 rng(seeder());
boost::random::uniform_int_distribution<unsigned long> gen(100,200);
std::cout << "in main:\n";
for (int c = 0; c < 10; c++)
std::cout << gen(rng) << "\n";
print_random_num(gen,rng);
std::cout << "\nback in main:\n";
for (int c = 0; c < 10; c++)
std::cout << gen(rng) << "\n";
}
catch (std::exception &e)
{
std::cout << "error encountered: " << e.what() << "\n";
}
return EXIT_SUCCESS;
}
// ---------- function definitions ----------
void print_random_num(boost::random::uniform_int_distribution<unsigned long> &gen, boost::random::mt19937 &rng)
{
try
{
std::cout << "\nin function:\n";
for (int c = 0; c < 10; c++)
std::cout << gen(rng) << "\n";
}
catch (std::exception &e)
{
throw;
}
}
程序的输出表明此方法有效,但是仅在输出中看到看似随机的数字并不一定意味着它确实有效。所以我有两个问题:
是测试程序中此处显示的方式,即通过引用,都是连续生成器rng
和分发对象gen
传递的正确方法,以便连续地 是否在整个程序中生成随机数?
如果我想在函数print_ran_num
内创建相同数字,并且在函数退出后 ,创建该函数就足够了,然后只需通过通过值生成器,即将函数签名更改为void print_random_num(boost::random::uniform_int_distribution<unsigned long> &gen, boost::random::mt19937 rng)
?再次,在这种情况下的输出表明这将正常工作。
给我的印象是,我曾经在documentation中看到了一个示例,用于Boost.Random,但现在找不到了。