5

In the code given below, I would like to implement a flag (or something equally simple) that has the same effect as commenting out the local setting and using the global setting some times (yielding two different numbers in this example), and using the local setting at other times (yielding two identical numbers in this example).

I have tried the obvious "if" and "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; } 
1
  • 1
    Can you please show how you have tried e.g. if or switch? Commented May 14, 2015 at 7:25

1 Answer 1

5

Use a ternary and a reference:

std::mt19937& ref = flag ? rng : local; 

Here, flag is the condition to test, rng is the "global" random object, and local is the more localised one.

Binding a reference to the result of a ternary is syntactically valid: you can't do it using an if statement, or similar as those are not expressions of the correct type.

From that point, use ref. This will be valid so long as rng and local remain in scope.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.