c++中rand()函数在不同的系统中可生成的最大数不同,现在我需要生成一个8位数的随机数,并放到数组中,并保证这个数组内的数全部都不重复,思路是生成两个四位的数,转换成字符串拼接后再转换为数字,存入数组中。
- // 生成大随机数
- int genTai(){
- int a = rand() %9999+1;
- int b = rand() %9999+1;
- string as = to_string(a);
- string bs = to_string(b);
- string res = as +bs;
- int result;
- istringstream is(res);
- is >> result;
- cout << result << endl;
- return result;
-
- }
-
- // 验证数是否存在数组中
- bool isCF(int re,vector<int> &target){
- for(int i:target){
- if(re == i)return 1;
- break;
- }
- return 0;
- }
- #include<bits/stdc++.h>
- using namespace std;
-
- // 上面的两个函数省略...
-
- int main(){
- // Random generator seed
- unsigned seed;
- seed = time(0);
- srand(seed);
-
- vector<int> target;
- int tlen = rand() % 99999+1;
- cout << tlen << endl;
- for (int i = 1; i <= tlen; ++i) {
- int re ;
- do{
- re = genTai();
- } while (isCF(re,target));
- cout << re << endl;
- target.push_back(re);
- }
-
- // use target ...
-
- return 0;
- }