Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我在C+中使用大量结构是正常的+;?_C++_Struct - Fatal编程技术网

C++ 我在C+中使用大量结构是正常的+;?

C++ 我在C+中使用大量结构是正常的+;?,c++,struct,C++,Struct,我非常喜欢使用结构,因为它们使我的代码更干净,但我担心这段代码使用了很多结构 struct action { int ex1 = 0; int ex2 = 0; int ex3 = 0; int ex4 = 0; }; struct state { // an array of the 'struct' action action actions[10]; }; int main() { state states[10]; } 这

我非常喜欢使用结构,因为它们使我的代码更干净,但我担心这段代码使用了很多结构

struct action {
     int ex1 = 0;
     int ex2 = 0;
     int ex3 = 0;
     int ex4 = 0;
};

struct state { // an array of the 'struct' action
     action actions[10];
};

int main() {
     state states[10];
}

这个代码是正确的吗?

< p>您可能需要考虑一些类型别名(<代码> TyPulfF/Code >使用< /Code >),而当您只有一个成员时,但并不总是更好。

你可能很好


拥有大量类型本身并不坏。

让我们分析一下您的结构:

struct action {
    int ex1 = 0;
    int ex2 = 0;
    int ex3 = 0;
    int ex4 = 0;
};
第一个结构存储4个整数

struct state {
    action actions[10];
};
第二个结构存储10个
action
s

int main() {
     state states[10];
}
最后,创建10个
state
s


很容易看出,您存储的都是整数。访问整数的一种快速方法是使用数组。第一个结构可以很容易地用4插槽阵列表示:

int action[4];    //action[0] = ex1; ...; action[3] = ex4;
第二个结构是一个包含10个动作的容器。它就像一个二维数组,在第一个维度中,你有10种可能性(即10个
动作
),在第二个维度中,你有4种可能性,即每个
动作
的4个值:

int state[10][4];    //state[3][2] = ex3 value from the 4-th action.
最后,创建一个包含10个状态的容器。按照相同的原则,您只需添加一个维度来存储10
state
s:

int states[10][10][4]    //states[1][2][3] = ex4 value from the 2-th action from the 1-st state.
这个三维阵列就是你所需要的。它可以用更少的空间表示您的结构,并更快地返回您的值

如果要设置操作,只需执行以下操作:

void set_action(int ex1, int ex2, int ex3, int ex4, int action, int state){`
    states[state][action][0] = ex1;
    states[state][action][1] = ex2;
    states[state][action][2] = ex3;
    states[state][action][3] = ex4;
}

在结构中封装一个数组的目的是什么?我编写的代码不是这样的,这只是一个例子。我可能应该投票结束这个问题,征求意见,但我不会。如果你开始这样做是为了保持秩序,后来又找到理由用别名之类的东西来减少秩序,那么你就有了一个好的开始——在我个人看来。我建议你展示一下使用你心目中的
struct
的替代方案,因为对
struct
是什么和不是有一些常见的误解,但由于你还没有深入研究任何细节,所以不清楚你用什么样的方法来考虑潜在的问题。如果该结构使代码更易于阅读、编写和维护,则该结构是合理的。