作为我自己的练习,我正在尝试创建一个可以求解方程的遗传算法。到目前为止,我的程序可以生成随机“基因”,用这些“基因”填充个体,并用这些基因做一些基本的计算(目前,只是简单地对“基因”求和)。
但是,我现在意识到我想要实现我的适应度函数,我最好为个体创建一个结构,因为我需要将基因和适应度结果放在一起,让最适合的基因再次繁殖.
无论如何,这是我的代码:
// GA.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <random>
#include <string>
const int population_size = 10;
const int number_of_variables = 7;
struct one_individual
{
std::vector<std::vector<double>>individual;;
double evaluation = 0;
double fit = 0;
};
int main()
{
// Generate random number
std::random_device rd;
std::mt19937 rng(rd()); // random-number engine (Mersenne-Twister in this case)
std::uniform_real_distribution<double> dist(-10.0, 10.0);
// Create vector that holds vectors called individual and fill size it to the amount of individuals I want to have.
std::vector<std::vector<double>>individual;
for (int i = 0; i < population_size; i++)
{
std::vector<double>variables;
for (int j = 0; j < number_of_variables; j++)
{
variables.push_back(dist(rng));
}
individual.push_back(variables);
}
// Display entire population
for (auto &count : individual)
{
for (auto &count2 : count)
{
std::cout << count2 << " ";
}
std::cout << "\n";
}
// Do calculation with population. At the moment I just add up all the genes (sum) and display the sum for each individual.
for (int i = 0; i < population_size; i++)
{
int j = 0;
std::cout << "Organism "<< i;
double sum = individual[i].at(j) + individual[i].at(j + 1) + individual[i].at(j + 2) + individual[i].at(j + 3) + individual[i].at(j + 4) + individual[i].at(j + 5) + individual[i].at(j + 6);
std::cout << " is " << sum << "\n";
}
std::cout << "\n";
return 0;
}
我认为我应该做的是这样的:
for (int i = 0; i < population_size; i++)
{
one_individual individual;
std::vector<double>variables;
for (int j = 0; j < number_of_variables; j++)
{
variables.push_back(dist(rng));
}
one_individual.individual.push_back(variables);
}
以上代码无效。当我尝试编译时发生的事情是我得到一个错误列表,我只是将它粘贴到 pastebin 中,因为它是一个相当大的列表:www.pastebin.com/EVJaV0Ex。如果我删除除“创建个人部分”所需的部分之外的所有内容,剩下的错误是:www.pastebin.com/djw6JmXZ。所有错误都在第 41 行,这是最后一行 one_individual.individual.push_back(variables);
为清楚起见进行了编辑,很抱歉不清楚。
最佳答案
考虑指令
one_individual.individual.push_back(variables);
其中 one_individual
是一个类型(struct one_individual
)。
我想你应该使用 one_individual
类型的已定义变量,所以
individual.individual.push_back(variables);
关于c++ - 使用结构/遗传算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37002622/