Strobe00 Strobe00 - 3 years ago 160
C++ Question

Generating randomized objects in a loop in c++

I have a person object class which is made up of name, address, and phone number object classes. The name, address, and phone number are randomly generated.

The user selects how many random people to generate and a function is called that generates them with a loop and stores them in a vector:

vector<Person> pV; //vector of people

for(int i = 0; i < num; i++){
Person x; //create new person object x
pV.push_back(x) //add to vector of people
cout << pV[i].getName(); //print for text

The problem is, all the objects generated are identical (same name, address, etc). If I generate a new list during the same session, a person with different information gets generated but they'll still all be identical.

I know this can happen in Java if you use static when randomizing... I'm not sure of the equivalent in C++.

Any suggestions?


Using just the name the person class is set up as follows:

Person class is set up as follows:

class Person{
Name name;

Name name;

The name class with random name generation is:

class Name{
public Name();
string generateName();
string name;

Name = generateName();

string Name::generateName(){
string Names[5] = {"a", "b", "C", "d", "e"};
int randomName = rand() % 5;
return Names[randomName];

Answer Source

With srand(time(NULL)); every name you generate reseeds the random number generator. If names are generated too quickly, under the 1 second resolution of time, the same seed will be used and the same sequence of random numbers will be generated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download