生成指定范围(1~)的不重复随机数

思路:先在容器中生成顺序的数据,再打乱。random_shuffle()函数的使用。

1-10不重复随机

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

using namespace std;

vector<int> randperm(int Num)
{
    vector<int> temp;
    for (int i = 0; i < Num; ++i)
    {
        temp.push_back(i + 1);
    }
    random_shuffle(temp.begin(), temp.end()); //打乱已存在容器中的数据
    
    return temp;
}
int main()
{
    vector<int> nums;
    nums = randperm(10);
    for (int i = 0; i < nums.size(); i++)
    {
        cout << nums[i] << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

【参考】

C++中随机数和不重复的随机数

c++ 将vector转化为数组

C++ 从函数返回数组

原文地址:https://www.cnblogs.com/xixixing/p/12367225.html