c++ - How do I switch between local and global settings for the initial state of a C++11 RNG? -
in code given below, implement flag (or equally simple) has same effect commenting out local setting , using global setting times (yielding 2 different numbers in example), , using local setting @ other times (yielding 2 identical numbers in example).
i have tried obvious "if" , "switch" structures without success.
#include <iostream> #include <random> void print(); std::seed_seq seed{1, 2, 3, 4, 5}; std::mt19937 rng(seed); // *global* initial state std::uniform_real_distribution<> rand01(0, 1); int main() { print(); print(); return 0; } void print() { std::mt19937 rng(seed); // *local* initial state std::cout << rand01(rng) << std::endl; }
use ternary , reference:
std::mt19937& ref = flag ? rng : local;
here, flag
condition test, rng
"global" random object, , local
more localised one.
binding reference result of ternary syntactically valid: can't using if
statement, or similar not expressions of correct type.
from point, use ref
. valid long rng
, local
remain in scope.
Comments
Post a Comment