C++11多个随机数引擎适配器

3

是否可以在C++11中同时使用STL提供的随机引擎和多个适配器?

例如,使用Mersenne Twister引擎与Discard Block engine adaptor(从每个大小为P的块生成的基础引擎中,适配器仅保留R个数字,丢弃其余数字)和Shuffle Order engine adaptor(以不同顺序提供随机数引擎的输出)。

以下是适配器的示例用法,以防您不熟悉:

//some code here to create a valid seed sequence
mt19937 eng(mySeedSequence);
discard_block_engine<mt19937,11,5> discardWrapper(eng);
shuffle_order_engine<mt19937,50> shuffleWrapper(eng);

for (int i=0; i<100; ++i) {
  //for every 5 calls to "discardWrapper()", the twister engine 
  //advances by 11 states (6 random numbers are thrown away)
  cout << discardWrapper() << endl;
}

for (int i=0; i<100; ++i) {
  //essentially 50 random numbers are generated from the Twister
  //engine and put into a maintained table, one is then picked from
  //the table, not necessarily in the order you would expect if you
  //knew the internal state of the engine
  cout << shuffleWrapper() << endl;
}

你是指是否可能调整一个已经适应的引擎?还是说同一基础引擎的输出可以以两种不同的方式适应? - T.C.
基本上,要同时拥有两个适应性的引擎。 - Victor Stone
1个回答

4
是的,您可以这样做。您只需要根据另一个适配器类型定义一个适配器类型即可:
typedef std::discard_block_engine<std::mt19937, 11, 5> discard_engine_t;
typedef std::shuffle_order_engine<discard_engine_t, 50> shuffle_engine_t;

std::mt19937 mt_eng;
discard_engine_t discard_eng(mt_eng);
shuffle_engine_t shuffle_eng(discard_eng);

好的,非常完美。非常感谢! - Victor Stone
为什么需要根据另一个定义一个,而不是按照问题中所写的那样做呢?任何对 mt19937::operator() 的调用都不会推进 rng 状态吗? - bernie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接