13

There is uniform_int_distribution in < random > When I creating that I define an interval. Can I change this interval after the creation?

for example

std::uniform_int_distribution distr(0, 10);
// can I change an interval here ?    
Evan Carslake
  • 2,267
  • 15
  • 38
  • 56
vlad4378
  • 803
  • 1
  • 9
  • 21

2 Answers2

14

Just assign a new distribution to the variable:

std::uniform_int_distribution<int> distr(0, 10);

distr = std::uniform_int_distribution<int>(5, 13);

Or, create a parameter for that (@awesomeyi answer required distribution object creation, this still requires param_type object creation)

std::uniform_int_distribution<int> distr(0, 10); 

distr.param(std::uniform_int_distribution<int>::param_type(5, 13));

Proof that param_type will work (for @stefan):

P is the associated param_type. It shall satisfy the CopyConstructible, CopyAssignable, and EqualityComparable requirements. It also has constructors that take the same arguments of the same types as the constructors of D and has member functions identical to the parameter-returning getters of D

http://en.cppreference.com/w/cpp/concept/RandomNumberDistribution

dreamzor
  • 5,795
  • 4
  • 41
  • 61
  • Is the `param_type` guaranteed to have an constructor taking two values? I can't find anything on cppreference.com – stefan Jul 12 '15 at 21:11
  • @stefan, for uniform_int_distribution? yes, you can see it by following the `param_type` declaration. – dreamzor Jul 12 '15 at 21:13
  • I don't see any requirement on the param_type constructors in the standard. Can you point me towards it? All I can see there is, that `param_type` is a `typedef unspecified param_type`. This would suggest, that there is no guarantee for such a constructor. – stefan Jul 12 '15 at 21:18
  • @stefan, added the link – dreamzor Jul 12 '15 at 21:21
  • I found the corresponding clause: it's 26.5.1.6 [rand.req.dist] 9. – stefan Jul 12 '15 at 21:24
2

You can through the param() function.

std::uniform_int_distribution<int> distr(0, 10);
std::uniform_int_distribution<int>::param_type d2(2, 10);
distr.param(d2);
yizzlez
  • 8,757
  • 4
  • 29
  • 44
  • 1
    i.e I need a new object anyway... It is sad :( – vlad4378 Jul 12 '15 at 21:07
  • @vlad4378 It's probably not that bad. You're not constantly switching ranges, right? And if the size of the range is the same for all, you can just add an offset. – stefan Jul 12 '15 at 21:08
  • @vlad4378 For example if you first use an distribution for values between 0 and 10, but later between 10 and 20, you can use the same distribution object, but simply add 10 to all values. – stefan Jul 12 '15 at 21:14
  • @ Thank you, it's way – vlad4378 Jul 12 '15 at 21:15
  • @stefan So, if i had ditr. between 0 to 10, and later 0 ... 7 , it doesn't help – vlad4378 Jul 12 '15 at 21:20