lundi 24 avril 2017

How to create obiects with random data member values? C++

All my obiects generated by code below have the same values for randomNumber1 and randomNumber2. How to properly use std::default_random_engine?

#include <random>
#include <iostream>

class Food{

    public:
        int randomNumber1;
        int randomNumber2;
        Food(){
            std::default_random_engine generator;
            std::uniform_int_distribution<int> distribution(1,40);
            std::uniform_int_distribution<int> distribution2(1,30);
            randomNumber1 = distribution(generator) * 20;
            randomNumber2 = distribution2(generator) * 20;
        };
};

int main(){

    Food * food = new Food();
    std::cout << food->randomNumber1 << " " << food->randomNumber2 << std::endl;
    Food * food1 = new Food();
    std::cout << food1->randomNumber1 << " " << food1->randomNumber2 << std::endl;
    Food * food2 = new Food();
    std::cout << food2->randomNumber1 << " " << food2->randomNumber2 << std::endl;

    return 0;
};




Aucun commentaire:

Enregistrer un commentaire