首页 > 其他 > 详细

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

时间:2020-02-26 15:50:26      阅读:70      评论:0      收藏:0      [点我收藏+]

思路:先在容器中生成顺序的数据,再打乱。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++ 从函数返回数组

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!