像自动点名机一样的魔法,
帮我们处理成堆的士兵和位置!
While 循环 (手动)像老师拿着名单,一个一个数: int i = 0; while(i < 5) { // 做事... i++; // 别忘了加1! } 容易忘记加 i++ 导致死循环! |
For 循环 (自动)像全自动点名机! for(int i=0; i<5; i++) { // 做事... // i 会自动增加 } 结构紧凑,不容易出错。 |
C++ For 循环语法:
auto friends = hero.findFriends(); // i 从 0 开始;只要 i 小于数量;每次 i 加 1 for(int i = 0; i < friends.size(); i++) { // 1. 找到第 i 个朋友 auto friend = friends[i]; // 2. 对他下命令 if (friend.type == "soldier") { hero.command(friend, "attack", enemy); } else { hero.command(friend, "move", target); } }
有时候我们有两份名单:
我们要让:
第 0 个士兵去第 0 个岗位,
第 1 个士兵去第 1 个岗位...
这时候,同一个索引 i 就可以同时控制两个数组!
你需要保护笼子的四个角。已经定义好了 4 个点。
auto points = {}; // 空数组 points[0] = {33, 42}; points[1] = {47, 42}; points[2] = {33, 26}; points[3] = {47, 26};
使用 For 循环 将朋友分配到这些点:
auto friends = hero.findFriends(); // i 同时作为 friends 和 points 的索引 for(int i=0; i < friends.size(); i++) { auto friend = friends[i]; auto point = points[i]; hero.command(friend, "move", point); }
int main() { // 1. 收集金币 (While) while(hero.gold < 80) { auto coin = hero.findNearestItem(); if(coin) hero.move(coin.pos); } // 2. 召唤 4 个士兵 (For) for(int i=0; i < 4; i++) { hero.summon("soldier"); } // 3. 分配岗位 (For + 双数组) auto friends = hero.findFriends(); for(int j=0; j < friends.size(); j++) { auto point = points[j]; // 假设 points 已定义 auto friend = friends[j]; hero.command(friend, "move", point); } return 0; }
while: 攒钱直到够了为止。for(i<4): 固定做4次召唤。for(i<size): 遍历数组发号施令。
这是 C++ 中最常用的循环结构,请牢记!
for ( 初始化 ; 条件 ; 变化 ) { ... }
例如:for (int i=0; i < friends.size(); i++)
int i = 0
i < size()
i++