C++ – 使用类参数定义向量大小

你好,我正在尝试用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指针)元素之后添加元素。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注