Random number generator in sets

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 #include <iostream>
#include <set>
#include <ctime>
#include <cstdlib>
using namespace 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();
	
}
Last edited on
Only do the srand(time(0)); in your constructor
Do you mean I should move the random number generator itself then? I'm a little confused.
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.
Last edited on
Topic archived. No new replies allowed.