I'm trying to do a random number generator inside of a set,but need some help. It works somewhat because the number generator works, but each random number is the same. Is there a way to make sure that each number is unique within the number generator? My code isn't done yet obviously, but just this portion to work.
#include <iostream>
#include <set>
#include <ctime>
#include <cstdlib>
usingnamespace std;
class Set {
public:
//default constructor
Set();
//add element to set
void addElement(int element);
//remove element from set
void removeElement(int element);
//check for membership
bool isMember(int element);
//set union, modifies curremtn set
void Union(Set s);
//set difference modifiers current set
void difference(Set s);
//size of set
int size();
//get element i
int getElement(int i);
private:
//binary search for element, returns index
bool search(int element, int& index);
//set members
//int elements[maxElements];
//next empty position in elements
int next;
};
Set::Set()
{
}
int Set::size()
{
srand(time(0));
int x = rand() % 25 + 1;
set<int> s{x};
set<int>::iterator it = s.begin();//iterator "it" starts at the begining of the set
int S_size;
cout << "Enter in the size of the set" << endl;
cin >> S_size;
for (int i = 0;i < S_size;i++)
{
cout << *it << " ";
}
return s.size();
}
int main(set<int>&)
{
Set enter;
enter.size();
}
srand(time(0)); should be moved to the top of main. This way you will get the same numbers when you the seed the random generator within the same second multiple times.
Is there a way to make sure that each number is unique within the number generator?
The random generator returns somewhat random numbers, hence they're no necessarily unique.
I think <random> has unique number options.
its rand mod 25 so another way for such a small set is to shuffle 0-24 (or 1-25 or whatever you actually want the end result to be) in a vector and just iterate it sequentially. Then you only get each value once, but don't ask for a 26th value!! <random> is powerful and c++, rand is C and very limited. I suggest you swap if you are allowed to do so.