我的程序是编写一个c ++程序,初始化一个大小为SIZE的整数向量v,每个向量均具有[0,2 * SIZE]范围内的不同随机整数,如何确保向量中的所有数字都是唯一的,如何编辑我的数字初始化向量,使其正常工作,在我的逻辑中有缺陷。无法使用随机播放。
#include <iostream>
#include <ctime>
#include <vector>
#include <iomanip>
#include<algorithm>
const int SIZE =10;
unsigned int seed = (unsigned)time(0);
using namespace std;
double random (unsigned int &seed);
void print_vector (vector<int> :: iterator b,
vector<int> :: iterator e );
void initialize_vector(vector<int> &v);
vector<int>v;
int main()
{
cout << endl;
initialize_vector(v);
cout << "Vector : " << endl;
print_vector(v.begin(), v.end());
return 0;
}
double random(unsigned int &seed)
{
const int MODULUS = 15749;
const int MULTIPLIER = 69069;
const int INCREMENT = 1;
seed = ((MULTIPLIER*seed)+INCREMENT)%MODULUS;
return double (seed)/MODULUS;
}
void initialize_vector(vector<int> &v)
{
vector<int> used;
int count_unused, k;
for (int i=0; i<2*SIZE; i++)
{
used.push_back(0);
}
for (int i=0; i<SIZE; i++)
{
int j= (random(seed)*(2*SIZE+1-i)) + 1;
count_unused = 0;
k = 0;
while (count_unused != j)
{
if (used[k] == 0)
count_unused++;
k++;
}
used[k] = 1;
v.push_back(j);
}
}
void print_vector (vector<int> :: iterator b,
vector<int> :: iterator e )
{
vector<int> :: iterator p =b;
while(p<e)
cout << setw(3) << (*p++);
cout << endl;
}
Run Code Online (Sandbox Code Playgroud)
std::iota和1做到这一点:std::random_shuffle
constexpr int SIZE = 10;
std::vector<int> values(2*SIZE+1);
std::iota(begin(values), end(values), 0);
std::random_shuffle(begin(values), end(values));
values.resize(SIZE);
Run Code Online (Sandbox Code Playgroud)
完整演示:http : //coliru.stacked-crooked.com/a/0caca71a15fbd698
首先,2*SIZE+1创建一个向量...
std::vector<int> values(2*SIZE+1);
Run Code Online (Sandbox Code Playgroud)
...,并填充从0到的连续整数2*SIZE。
std::iota(begin(values), end(values), 0);
Run Code Online (Sandbox Code Playgroud)
我们将这些价值观洗牌了...
std::random_shuffle(begin(values), end(values));
Run Code Online (Sandbox Code Playgroud)
...并删除第二部分。
values.resize(SIZE);
Run Code Online (Sandbox Code Playgroud)
瞧
1)注意:这是C ++ 11/14解决方案,std::random_shuffle自C ++ 14起不推荐使用,并已在c ++ 17中删除。