这篇文章主要为大家详细介绍了C++生成不重复的随机整数,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
C++生成不重复的随机数,供大家参考,具体内容如下
给定正整数的范围[n,m],生成k个不重复的随机数字。
IDE是vs013。
#include "stdafx.h" #include #include #include #include #include using namespace std; int _tmain(int argc, _TCHAR* argv[]) { srand((unsigned)time(NULL)); list::iterator it;//迭代器 list l;//定义链表,保存生成的随机数 int begin, end;//数字范围 int sum;//随机数个数 cout <>begin>>end; cout <> sum; if ( (end<0)||(beginend)|| (sum>end))//起始范围必须大于0,且随机数个数小于等于最大数字范围 { cout << "范围错误"; cout << endl; system("pause"); return 0; } else { while (l.size() <sum) { l.push_back(rand() % (end - begin + 1) + begin); l.sort();//排序 l.unique<div style="color:transparent">来源gaodai^.ma#com搞#代!码网</div>();//去除相邻的重复随机数中的第一个 } cout << "结果:"; } for (it = l.begin(); it != l.end(); it++) { cout << *it << ' '; } cout << endl; system("pause"); return 0; }
运行结果:
这个程序可以用于班级内部按照学号进行随机抽签。
以上就是C++生成不重复的随机整数的详细内容,更多请关注gaodaima搞代码网其它相关文章!