C++-用类参数定义矢量大小
C++ - Define Vector size with class argument
你好,我试图用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
中的初始(在本例中为空指针)元素之后添加元素。
- 部分定义/别名模板模板参数
- 有没有办法使用 googletest 创建自定义参数生成器?
- 使用自定义参数的过载删除操作员
- C++ 默认参数的重新定义:参数 1 (矢量 2D)
- Cython:具有自定义参数类型的STD ::功能回调
- 让我们C++推断定义参数的类/命名空间的位置
- 将自定义参数传递到Qt/C++中的插槽
- 定义参数包扩展的"pattern",尤其是在函数调用中
- 使用自定义参数进行 QAction
- 具有未定义参数的私有副本构造函数
- Qt-具有自定义参数的可重用绘制函数
- 类型定义参数的重载
- 如何调用定义参数为空的函数
- 如何正确使用作为其他定义参数的定义?C++
- 框架的用户定义参数应该在哪里
- 带有自定义参数的Sendmessage /postmessage
- c++定义参数重载
- Boost c++ Phoenix用户定义参数的下标操作符[]错误
- 是否可以在预处理器中定义参数化列表?
- c++中可变的用户定义参数列表