向量C ++中的非重复随机数

时间:2017-11-10 22:56:38

标签: c++ vector random numbers

我试图在矢量中存储随机数,但我希望每个数字都是唯一的。我可以使用for循环而不使用unique()或random_shuffle()吗?

#include <iostream>
#include <vector>
#include <ctime>

using namespace std;

int main()
{

    srand(time(NULL));

    vector<int> v;

    for (unsigned int i = 0; i < 30; i++) {

          v.push_back(rand() % 30);
    }

    for (unsigned int j = 0; j < 30; j++) {

        cout << v[j] << endl;
    }

    return 0;
}

2 个答案:

答案 0 :(得分:4)

经典Fisher–Yates shuffle也可用于直接生成混洗向量,一次传递

vector<unsigned> v;

for (unsigned i = 0; i < 30; ++i)
{
  unsigned j = rand() % (i + 1);
  if (j < i)
  {
    v.push_back(v[j]);
    v[j] = i;
  }
  else
    v.push_back(i);
}

答案 1 :(得分:2)

您应该生成矢量并将其随机播放:

#include <iostream>
#include <ctime>
#include <utility>

int main()
{

    std::srand(static_cast<unsigned int>(std::time(NULL)));
    size_t const n = 30;
    std::vector<int> v(n);

    //make vector
    for (size_t i = 0; i < n; ++i)
        v[i] = static_cast<int>(i);

    //shuffle
    for (size_t i = n - 1; i > 0; --i)
        std::swap(v[i], v[static_cast<size_t>(rand()) % (i + 1)]);

    //print
    for (size_t i = 0; i < n; ++i) 
        std::cout << (i > 0 ? "," : "") << v[i];

    return 0;
}

打印,例如:

27,24,2,23,13,6,9,14,11,5,15,18,16,29,22,12,26,20,10,8,28,25,7,4,1,17,0,3,19,21