Results 1 to 2 of 2

Thread: random vector of numbers

  1. #1
    Senior Member
    Join Date
    Apr 2002

    random vector of numbers


    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 "iostream"
    #include "vector"
    #include "time.h"
    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<int> Selection(NumElements);

    for(unsigned int i = 0; i <= Selection.size() - 1; i++)
    Selection[i] = GiveRandInt( MaxElementSize );
    cout << "element " << i << ": " << Selection[i] <<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. #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()):
    BTW, the way to get the clock ticks since program start is "clock()" and that is included in <ctime> (the c++ name for <time.h&gt. If you want to use clock ticks along with the time use this line instead:
    srand(time(NULL) + clock());

Similar Threads

    By Fatal Error in forum General Chat
    Replies: 1
    Last Post: 12-25-2005, 08:08 PM
  2. Vector 5.0 RC2 is out...
    By mcangeli in forum Linux - General Topics
    Replies: 0
    Last Post: 07-01-2005, 06:52 AM
  3. Vector Graphics For Linux
    By Fatal Error in forum General Chat
    Replies: 2
    Last Post: 02-24-2005, 10:00 AM
  4. Random numbers in python
    By airhead in forum Linux - Software, Applications & Programming
    Replies: 7
    Last Post: 07-30-2002, 06:03 AM


Posting Permissions

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