c++ - 使用结构/遗传算法

标签 c++ algorithm c++11 vector struct

作为我自己的练习,我正在尝试创建一个可以求解方程的遗传算法。到目前为止,我的程序可以生成随机“基因”,用这些“基因”填充个体,并用这些基因做一些基本的计算(目前,只是简单地对“基因”求和)。

但是,我现在意识到我想要实现我的适应度函数,我最好为个体创建一个结构,因为我需要将基因和适应度结果放在一起,让最适合的基因再次繁殖.

无论如何,这是我的代码:

// 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/

相关文章:

algorithm - 找到数组中 n 个元素的最大总和,使得不超过 k 个元素相邻

java - 如何设计一个高效的排序对手?

c++ - SFINAE 在返回类型中工作但不作为模板参数

c++ - 从函数返回一个shared_ptr

c# - 什么会导致进程停止重新创建?

c++ - C++中迭代器的返回

算法:具有约束 max-min<=diff 的随机分布

c++ - ={} 和 {} 风格的初始化在 C++11 中是否相同?

c++ - 从类型的右值初始化类型的非常量引用无效

c++ - 如何调用同名不同参数的虚函数?