你好,我正在尝试用C++创建一个遗传算法,并尝试使用向量作为容器,但问题是我不知道如何设置向量的大小,因为向量有一个类参数,像这样
class population{ friend class chromosome;private: int population_number; int best_index[2]; vector <chromosome *> chromosome_population;public: population(int numberOfPopulation); population(int numberOfPopulation,int numberOfSynapse); ~population(); int worst_chromosome(); void mating(); void crossover(int parent_1,int parent_2);};
这是种群类,以下是染色体类
class chromosome{ friend class population;private: int chromosome_id; float fitness; vector <gen *> gen_chromosome;public: chromosome(); ~chromosome(); void fitness_function(); void mutation_translocation(); int get_chromosome_size();};
我如何在种群类的构造函数中设置向量长度?我尝试使用vector.pushback和vector.resize,但两者都会因为参数不匹配而报错。实际上我明白为什么会报错,但我不知道如何在vector pushback中匹配参数。这是我的种群构造函数
population::population(int numberOfPopulation){ srand (time(NULL)); population_number = numberOfPopulation; for(int a=0;a<population_number;a++) { chromosome_population.push_back(); } cout<<chromosome_population.size(); for(int i=0;i<population_number;i++) { chromosome_population[i]->chromosome_id = i; int chromosome_length = rand() % 10 + 1; for(int j=0;j<chromosome_length;j++) { chromosome_population[i]->gen_chromosome[j]->basa_biner = rand()%1; chromosome_population[i]->fitness = (rand()%99)+1; } }}
如果你需要其他信息,可以在评论中告诉我,我会添加你需要的信息。谢谢。
回答:
std::vector
有几个构造函数,其中一个变体接受要存储在vector
中的初始元素数量。
在population
构造函数的初始化列表中指定vector
的大小:
population::population(int numberOfPopulation) : population_number(numberOfPopulation), chromosome_population(numberOfPopulation){}
采用这种方法,population_number
成员变量是不必要的,因为它可以通过chromosome_population.size()
获得。
在vector
上指定初始大小意味着它包含numberOfPopulation
个空指针。在访问vector
中的元素之前,你需要创建对象,在这种情况下使用new
。如果元素是可复制的且不需要多态行为,则建议使用vector<chromosome>
。如果你必须在vector
中使用动态分配的元素,那么你必须首先分配:
chromosome_population[i] = new chromosome();
并且记得在不再需要时使用delete
删除它们。
使用智能指针代替原始指针也是可取的。使用智能指针的一个优点是,当vector<unique_ptr<chromosome>>
超出作用域时,元素将为你销毁,而无需在每个元素上显式调用delete
。有关可用智能指针的有用列表,请参见What C++ Smart Pointer Implementations are available?。
请注意,vector::push_back()
接受一个参数,其类型与其元素相同。因此,push_back()
的正确调用方式是:
chromosome_population.push_back(new chromosome());
如果你在构造时指定了vector
的初始大小,调用push_back()
将在vector
中的初始(在这种情况下为null指针)元素之后添加元素。