快速生成N个不重复随机数
实现代码
#include <ctime>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
vector<int> getRandom(int low, int high, int n) {
int size = high - low + 1;
int* seed = new int[size];
for (int i = low; i <= high; i++)
seed[i - low] = i;
vector<int> ans;
srand(time(nullptr));
for (int i = 0; i < n; i++)
{
int r = rand() % size;
ans.push_back(seed[r]);
swap(seed[r], seed[--size]);
}
delete seed;
return ans;
}
int main() {
vector<int> ans = getRandom(1,100,50);
for_each(ans.begin(), ans.end(), [](int t)->void {
cout << t << endl;
});
return 0;
}