C ++迭代结构 [英] C++ iterating a struct
本文介绍了C ++迭代结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以遍历结构?
例如
struct team{
int player1;
int player2;
int player3;
int player4;
...
int player99;
int size = 99;
}
然后运行for循环设置或访问foo 1-4?
then run a for loop to set or access foo 1-4?
我猜伪代码看起来像
for(int i = 0; i < size; i++){
player i = (i+1);
}
如果没有意义,更简单的解释是我只想要能够无需硬编码player1 = 1即可浏览每个变量; player2 = 2.
A more simplified explanation if that doesnt make sense is I Just want to be able to go through each variable without having to hard code player1 = 1; player2 =2.
推荐答案
一种方法是将玩家/元素放入数组:
One way is to put the players/elements into an array:
struct Team {
static int const size = 99;
int players[size];
};
然后:
for(int i = 0; i < size; ++i)
int player = players[i];
这篇关于C ++迭代结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文