2017-04-24 78 views
1

下面的代碼生成的所有對象對於randomNumber1和randomNumber2具有相同的值。如何正確使用std :: default_random_engine?如何用隨機數據成員值創建對象? C++

#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; 
}; 

回答

3

那是因爲你重新播種的engine(使用相同的種子),每次創建一個Food對象。你可以做的是讓它static所以才播種一次:

static 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; 

或..讓來電者決定的種子。

或者,如@Unimportant在評論中說,使用std::random_device

static std::random_device dev; 
static std::default_random_engine generator(dev()); 
+0

或者更好的是,將它作爲一個構造函數參數。 'static' ...這取決於調用者決定:) – xtofl

+1

或者使用'std :: random_device'來獲得一個真正的隨機種子。 – Unimportant

+0

@不重要是的,補充說。 –