产生n个小于等于m的不重复随机整数

来源:互联网 发布:语音信箱软件 编辑:程序博客网 时间:2024/05/18 06:19


本题的关键在于随机数的不重复.

STL中的set , 往里面插入重复数时,会插入失败, 本例就是利用了set 自带的这个插入特性, 保证随机数的不重复。


#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<set>
#include<iostream>
using namespace std;
int main(void)
{
 int m, n;
 cout << "please input m and n, and make sure m >n " << endl;
 cin >> m;
 cin >> n;

 set <int> s;
 srand(time(NULL));
 for (int i = 0; i < n; i++)
 {
  int random = rand() % m + 1;
  if (s.insert(random).second)
   cout << "insert ok" << endl;
  else
  {
   while (1)
   {
    random = rand() % m + 1;
    if (s.insert(random).second)
     break;
   }
  }

  cout << random << endl;
 }
 system("pause");
 return 0;

}

阅读全文
0 0
原创粉丝点击