1

我创建了一个全局向量。之后,我使用 push_back 函数添加值。但是,当我想获取向量的任意索引时,它总是返回被推送的最后一个值。代码如下:

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 );
}
4

1 回答 1

4

问题是您srand(time(NULL));每次迭代都在播种。

如果您检查生成的数字,您会发现它们对于每个Chromosome.

您要么必须取消它forsrand()要么给它一个当前时间参数。

于 2012-12-19T00:27:57.677 回答