For fun im making a singleton that is used to shuffle an array. Im trying to shuffle an array in c++ with std::shuffle, but the shuffle produces the same result everytime I run the program.
The code:
// Example program
#include <iostream>
#include <string>
#pragma once
#include <memory>
#include <random>
#include <ctime>
#include <algorithm>
class RandomPicker
{
public:
~RandomPicker();
std::default_random_engine getRandomEngine();
static std::shared_ptr<RandomPicker> getInstance();
private:
std::default_random_engine dre = std::default_random_engine(time(0));
RandomPicker();
static std::shared_ptr<RandomPicker> instance;
};
std::shared_ptr<RandomPicker> RandomPicker::instance = nullptr;
RandomPicker::RandomPicker()
{
}
RandomPicker::~RandomPicker()
{
}
std::default_random_engine RandomPicker::getRandomEngine()
{
return std::default_random_engine();
}
std::shared_ptr<RandomPicker> RandomPicker::getInstance()
{
if (instance == nullptr)
{
instance.reset(new RandomPicker);
}
return instance;
}
int main()
{
std::array<int,5> foo {1,2,3,4,5};
std::shared_ptr<RandomPicker> r = RandomPicker::getInstance();
shuffle (foo.begin(), foo.end(), r->getRandomEngine());
std::cout << "shuffled elements:";
for (int& x: foo) std::cout << ' ' << x;
std::cout << '\n';
}
I thought using
std::default_random_engine dre = std::default_random_engine(time(0));
//notice the time(0)
would get a different result everytime, but the result equals to.
shuffled elements: 3 1 5 4 2
Why is the array not sorted in a different way everytime the program runs?