C++生成无重复随机数组

C++ 中生成随机数可以使用rand()函数,可是如果想要生成无重复的随机数组,单单使用这个就不行了,因为即使循环生成随机数,赋值给数组,也会有重复的,所以要使用以下的代码

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

void randperm(int Num)
{
    vector<int> temp;
    for (int i = 0; i < Num; ++i)
    {
        temp.push_back(i + 1);
    }
    random_shuffle(temp.begin(), temp.end());
    for (int i = 0; i < temp.size(); i++)
    {
        cout << temp[i] << " ";
    }
}

int main()
{
  randperm(10);
  return 0;
}

第一个循环是将要生成多少个数,放到vector<int> 中,使用random_shuffle(temp.begin(), temp.end()),是为了将其中的数字打乱排序,再从头输出的就是随机数了。

发布了36 篇原创文章 · 获赞 11 · 访问量 6553

猜你喜欢

转载自blog.csdn.net/t20134297/article/details/89930307