【问题标题】:C++ Problem filling structs with values from another structC++ 用来自另一个结构的值填充结构的问题
【发布时间】:2018-11-13 22:26:04
【问题描述】:

我在试图弄清楚为什么我没有通过一段代码获得正确的功能时遇到了问题。我环顾四周,试图找到一个解决方案,但是我一直没能做到。以下是我的代码示例:

//Structs
typedef struct
{
    int gene[60];
    int fitness;

} individual;

typedef struct
{
    int cond[5];
    int out;
}rule;

//Array of individuals
individual population[P]

int function(individual solution){
    int k = 0;
    //Array of rules
    rule rulebase[10]
    for (int i = 0; i < 10; i++){
        for (int j = 0; j < 5; j++){
            rulebase[i].cond[j] = solution.gene[k++];
        }
        rulebase[i].out = solution.gene[k++];
    }

    for (int i = 0; i < 5; i++){
        cout << rulebase[0].cond[i];
    }

传入函数的解是'population'中的第一个个体,基因数组只包含二进制数,例如:

gene = [0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1] //There will be 60 in total

所需的功能是用在解决方案中找到的值填充规则库中的规则结构。例如,使用上面的示例,规则库中的第一条规则将在 'cond' 数组中具有以下值:

[0, 0, 1, 0, 1]

'out' 将是解中的下一个整数:

[1]

然后下一条规则将以相同的方式填充解决方案中的下一个值。

我遇到的问题是代码似乎用解决方案中的所有值填充每个规则的“cond”数组,这与上述所需方式相反。例如,当我打印 'rulebase[0]' 中的基因时,我得到:

[0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1]

反对:

[0, 0, 1, 0, 1]

我似乎无法弄清楚为什么我会遇到这个问题,因为代码在我看来应该可以工作?任何帮助将不胜感激,因为我正在努力奋斗!

【问题讨论】:

  • 无关:C++ 从 20 多年的 C 中学到了很多东西,并允许您将 typedef struct { ... }rule; 写成 struct rule{ ... };

标签: c++ arrays struct


【解决方案1】:

一条规则在cond 中只包含 5 个值,而不是您显示的 10 个。它只是您的代码打印了错误的rulebase[0] 的值,即它超出了数组边界并打印 - 除了rulebase[0]cond 值之外 - 的outcond 的值下一条规则,在记忆中——接下来是。

【讨论】:

    猜你喜欢
    • 2017-06-08
    • 1970-01-01
    • 2013-10-29
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多