C ++:为什么这个方法每次都返回相同的随机数?

时间:2018-05-08 14:36:21

标签: c++ random

我有一个类,它有一些存储在向量中的数据和一个应该选择随机元素并返回它的方法,但是当我运行它时,它每次都返回相同的元素。

以下是基于我的代码的简化示例:

#include <iostream>
#include <random>
#include <vector>

class MyObj{
  private:
    std::vector<int> set_data;

  public:
    MyObj(int num_elements){
      for (int i = 0; i < num_elements; ++i){
        set_data.push_back(i); // just so that there is some data in there
      }
    };
    int getRandomElement(std::mt19937 rng){
      std::uniform_int_distribution<int> uni(0,set_data.size()-1);
      int idx = uni(rng);
      return set_data[idx];
    };
};


int main()
{
  std::random_device r;
  std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
  std::mt19937 rng = std::mt19937(seed);

  MyObj temp(50);

  for (int i = 0; i < 20; i++){
    std::cout << "getting random element: " << temp.getRandomElement(rng) << std::endl;
  }
}

,输出为:

getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19
getting random element: 19

有什么明显的我在这里做错了吗?

1 个答案:

答案 0 :(得分:5)

int getRandomElement(std::mt19937 rng){
  std::uniform_int_distribution<int> uni(0,set_data.size()-1);
  int idx = uni(rng);
  return set_data[idx];
};

这是通过值传递,这意味着RNG的状态将从原始状态复制,原始状态永远不会更新。更改此方法以通过引用传递应该可以解决问题。

int getRandomElement(std::mt19937 & rng){