# Thread: random vector of numbers

1. ## random vector of numbers

hi,

Im trying to create a vector of random integers in C++. Im trying to seed the rand()
function w/ the time that the system have been up. but it just gives me a vector of same numbers. running again gives a different set of same numbers. Can anyone tell my how to seed the the rand function correctly

here's my code

#################
#include &quot;iostream&quot;
#include &quot;vector&quot;
#include &quot;time.h&quot;
using namespace std;

int GiveRandInt(int N); // returns a random integer from 0 to N-1

int main()
{

int NumElements = 10;
int MaxElementSize = 100;

vector&lt;int&gt; Selection(NumElements);

for(unsigned int i = 0; i &lt;= Selection.size() - 1; i++)
{
Selection[i] = GiveRandInt( MaxElementSize );
cout &lt;&lt; &quot;element &quot; &lt;&lt; i &lt;&lt; &quot;: &quot; &lt;&lt; Selection[i] &lt;&lt;endl;
}

return 0;
}

int GiveRandInt(int N)
{

srand(time(NULL)); // Seed our random numbers w/ time

//srand(GetTickCount()); // I saw a place use this but it doesn't work here. Anyone know if I need some special header for this to work?

int RandNum = rand() % N;
return RandNum;
}
#################

2. ## Re:random vector of numbers

The reason you are getting the same number every time is that you are reseeding it every time you want to get a random number. You only need to seed it once.

Put this line at the beginning of main() (and remove it from GiveRandInt()):
Code:
`srand(time(NULL));`
BTW, the way to get the clock ticks since program start is &quot;clock()&quot; and that is included in &lt;ctime&gt; (the c++ name for &lt;time.h&gt. If you want to use clock ticks along with the time use this line instead:
Code:
`srand(time(NULL) + clock());`

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•