【问题标题】:Fill vector with unrepeated random numbers. why not working?用不重复的随机数填充向量。为什么不工作?
【发布时间】:2015-12-09 10:59:10
【问题描述】:

我已经看到了基于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)) 

这会创建一个包含重复随机数的向量。这里有什么问题?

【问题讨论】:

  • 在我看来,您正在对未排序的列表使用二进制搜索,这需要排序列表。当您生成不在列表中的新数字时,您应该进行插入排序,以便列表中的数字保持排序状态。
  • 作为一项改进,您可以将vector 声明更改为std::vector&lt;int&gt; ret(v_size);
  • 只是一个让你的代码更具可读性的建议,你可以把这个 if (ret.size() > 0) 改成这个 if(!ret.empty() ) 它基本上和vector一样::size() 将返回一个无符号整数。抱歉是小错字,重新发表评论:)

标签: c++


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    相关资源
    最近更新 更多