1

I create a global vector. After that I add values with push_back function. But, when I want to get an arbitrary index of vector, it always returns the last value that was pushed. The code is the following:

struct Choromosome{
    float fitness;
    float selectionProb;
    bool isSelected;
    int conflictNum;
    int* geneCode;
};
int SIZE = 6;
int START_SIZE = 50;
vector<Choromosome> population;

void initialize(){
  for(int k = 0; k < START_SIZE; k++){
     Choromosome c;
     int* code = new int[SIZE];
     srand(time(NULL));
     for(int i = 0; i < SIZE; i++){
        code[i] = rand() % SIZE;
     }
     c.geneCode = code;
     population.push_back(c);
  }
  int rand1 = rand() % START_SIZE;
  int rand2 = rand() % START_SIZE;     
  std::ostream_iterator< int > output( cout, " " );
  std::copy( population[rand1].geneCode, population[rand1].geneCode+ SIZE, output );
  std::copy( population[rand2].geneCode, population[rand2].geneCode+ SIZE, output );
}
imreal
  • 10,178
  • 2
  • 32
  • 48
user1914367
  • 171
  • 1
  • 2
  • 12

1 Answers1

4

The problem is that you are seeding with srand(time(NULL)); every iteration.

If you check the generated numbers, you'll see they are the same for every Chromosome.

You either have to take out of the for that srand() or give it a current time parameter.

imreal
  • 10,178
  • 2
  • 32
  • 48
  • Thank you, this solve this problem. Hovewer when i call two indexes of the population from another function, it still returns the last index, although i don't use rand. – user1914367 Dec 19 '12 at 09:42