C++指针和队列

C++ Pointers and queues

本文关键字:队列 指针 C++      更新时间:2023-10-16

我正在尝试制作一个让两支球队相互对抗的程序。 每支球队都有相同数量的球员。 假设球队 1 有球员 A、B、C、D,队 2 有球员 E、F、G、H。
在第 1 回合中,玩家 A 对阵玩家 E。 假设 A 赢了。 然后 A 回到他的团队(我把它排进了队列),所以团队 1 现在有球员 B、C、D、E。 B 进入失败者堆栈(所以我从团队 2 中弹出它并将其推送到一个名为 loser 堆栈的新队列)。
然后在第 2 回合,玩家 B 对阵玩家 F。 依此类推,直到只剩下 1 支球队的球员。

我无法弄清楚执行此操作的算法。 我不是在寻找特定的代码(或任何做我工作的人在做我的工作),我只是想要一些关于人们如何做到这一点的想法。 我还没有学过映射,我只允许指针和基本函数。 我的猜测是我必须做某种 for 循环,例如:

for (int i = 0; i < 4; i++){         //this is the loop for team 1, with 4 players
   for (int j = 0; j < 4; j++) {     //this is the for loop for team 2
       //this is the part I need help with:
       //somehow I need to call a player from team 1 from the queue
       //and also call a player from team 2
   }
}

有没有办法从队列中调用某些东西? 任何建议将不胜感激。 非常感谢您的帮助!

使用两个std::queue实例 - 每个团队一个。一开始,用玩家填充它们。然后,执行单个 for 循环以迭代 roud。在每个回合中,使用std::queue::pop从每个团队中获取下一个玩家。选择获胜玩家后,使用push将获胜玩家放回其团队队列的末尾。

int fight(Player &p1, Player &p2)
{
    int result = 0; // 1 if p1 wins, 2 if p2 wins
    // ...
    return result;
}

然后你可以做这样的事情:

std::queue<Player> team1;
std::queue<Player> team2;
std::queue<Player> losers;
while(team1.size() > 0 && team2.size() > 0) {
Player p1 = team1.front();
team1.pop();
PLayer p2 = team2.front();
team2.pop();
int result = fight(p1, p2);
if(result == 1) {
    team1.push(p1);
    losers.push(p2);
} else {
    team2.push(p2);
    losers.push(p1);
}
}