C++-用类参数定义矢量大小

C++ - Define Vector size with class argument

本文关键字:定义 参数 C++-      更新时间:2023-10-16

你好,我试图用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,但由于参数不匹配,两者都会给我带来错误。事实上,我理解它为什么会出错,但我不知道如何匹配向量推回中的论点,这是我的总体构造函数

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();

并在不再需要时记住CCD_ 13。

还希望使用智能指针的形式而不是原始指针。使用智能指针的一个优点是,当vector<unique_ptr<chromosome>>超出范围时,将为您销毁元素,而不必在每个元素上显式调用delete。请参阅有哪些C++智能指针实现可用?以获取可用智能指针的有用列表。

注意,vector::push_back()接受一个参数,其类型与其元素相同。因此push_back()的正确调用是:

chromosome_population.push_back(new chromosome());

如果在构造时指定vector的初始大小,则调用push_back()将在vector中的初始(在本例中为空指针)元素之后添加元素