2

I made a class with a function that returns a randomly generated pair<int, int> to represent a coordinate pair. At the beginning of the function I have srand(time(NULL)) and I use rand() % 50 to get the random number pair.

It works great... as long as I only have one object of that. If I have two different objects of that class and call the function for each object (by this I mean trying to generate two different random coordinates for two different objects of this class), it returns the exact same coordinate pair for each object.

In retrospect, I can understand why this happens -- because I'm getting the random number based off of the current time, right? But what method should I use to return a random pair EVERY TIME I call that class's function?

phuclv
  • 37,963
  • 15
  • 156
  • 475
UnworthyToast
  • 825
  • 5
  • 11
  • 21
  • 8
    1. Call `srand` **once** at the beginning of your program and **never** again. (unless you're purposely reproducing a seeded sequence). And 2. Stop using `srand()` and `rand()` altogether and start using the [``](http://en.cppreference.com/w/cpp/numeric/random) library instead. Its the cat's whiskers. – WhozCraig Mar 24 '14 at 08:24
  • 2
    See this good talk about [why rand can be considered harmful by STL](http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful). – JBL Mar 24 '14 at 08:29
  • Possible duplicate of [srand() — why call it only once?](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once) – phuclv Oct 11 '17 at 16:51

1 Answers1

1

At the beginning of the function I have srand(time(NULL))

Call srand() once at the beginning of your program and never again.

PS: Consider using <random> instead of C-traditional functions.

gsamaras
  • 71,951
  • 46
  • 188
  • 305