1

I am trying to set seed to the c++ std::default_random_engine:

#include<random>
#include<time.h>
#include<iostream>

using namespace std;


void print_rand();


int main() {

for (int i{0}; i < 20; ++i) {
    print_rand();
}
return 0;
}

void print_rand() {
    default_random_engine e;
    e.seed(time(0));

    cout << e() << endl;
}  

It seems that the printed numbers are same, how could I set the seed to generate the random number according to the time?

coin cheung
  • 949
  • 2
  • 10
  • 25

2 Answers2

3

You have to seed only once instead of every time the function is called. Then you will get different values. I will move the functionality to main() to demonstrate this.

#include<random>
#include<time.h>
#include<iostream>

int main() {
    std::default_random_engine e;
    e.seed(time(0));

    for (int i{0}; i < 20; ++i) {
        std::cout << e() << std::endl;
    }
    return 0;
}

See Live Demo

P.W
  • 26,289
  • 6
  • 39
  • 76
  • What if I do not have a main? I am actually writing some python extension, then I have no main function. – coin cheung Feb 22 '19 at 09:43
  • 2
    That's just an example I have given to demonstrate the right behavior. The point is you have to **seed only once**. – P.W Feb 22 '19 at 09:49
  • Hi, will the seed be set for the whole process. If I set the seed in some function, will the settings still work after the function is returned? – coin cheung Feb 23 '19 at 03:20
  • Yes, you can have a static variable inside the function that you seed only once. – P.W Feb 23 '19 at 04:11
2

As @P.W. said, you should seed only once. A minimal change in that direction would be using a static variable with the seed given to the constructor:

#include<random>
#include<time.h>
#include<iostream>

void print_rand();

int main() {
    for (int i{0}; i < 20; ++i) {
        print_rand();
    }
    return 0;
}

void print_rand() {
    static std::default_random_engine e(time(0));

    cout << e() << endl;
}
Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75