用未重复的随机数填充矢量。为什么不工作?

时间:2015-12-09 10:59:11

标签: c++

我已经看到了基于std::random_shuffle创建未重复随机数向量的方法,但是我需要实现一种替代方法。这是我的代码:

std::vector<int> create_unrepeated_random(int v_size, int v_max) {

  // Max index value must be grater than the number of vector size
  assert(v_max > v_size);

  std::vector<int> ret;

  int val = 0;

  for (int i = 0; i < v_size; i++) {

    val = std::rand() % v_max; 

    // Keep generating new values until we generate one that is not already in  
    // output vector
    if (ret.size() > 0) {
      while (!std::binary_search(ret.begin(), ret.end(), val)) {
        val = std::rand() % v_max; 
      }
    }

    ret.push_back(val);

  }


  assert ((int)ret.size() == v_size);
  for (auto &v: ret) printf("%d ", v);printf("\n");

  return ret;

}

然而,这不起作用,不知道为什么。有些数字有时会被重复。

但如果我将while循环更改为

 while (std::binary_search(ret.begin(), ret.end(), val)) 

这会创建一个重复随机数的向量。这有什么不对?

1 个答案:

答案 0 :(得分:4)

std::binary_search

仅适用于已排序的范围。请改用std::find

while (std::find(ret.begin(), ret.end(), val) != ret.end())

或者,您可以使用std::unordered_set

std::unordered_set<int> ret;
while (ret.size() < v_size) {
    ret.insert(rand() % v_max);
}

请记住,使用这种方法,生成的数字的顺序将是未指定的,即可能比矢量方法更不随机。如果您想要一个排序的随机数序列,请考虑std::set

备注:在现代C ++中不鼓励使用rand(),尽管它可能会对玩具程序起作用。另请参阅https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

相关问题