C++指针和队列
C++ Pointers and queues
我正在尝试制作一个让两支球队相互对抗的程序。 每支球队都有相同数量的球员。 假设球队 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);
}
}
相关文章:
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 使用"Task"函数指针队列定义作业管理器
- 向量成员在管理类指针C++队列时丢失
- 更改队列指针成员的值需要在 C++ 中出现奇怪的错误
- 队列数组指针 (C++)
- 队列未正确插入指针
- 复制的队列更改 打印临时队列后队列的头部指针指向空 队列
- 为什么我的简单C++程序使用队列和 fstream 错误到无效指针
- 实现指针队列
- 用指针清理队列时,无尽的环路
- 从指针队列访问结构的成员
- 优先级队列实现为单一链接,无法更新插入的指针转换
- 如何通过队列指针访问存储在节点中的类中的数据
- 使用无锁指针队列在线程之间移动数据是否安全
- C++:在队列中丢失指针值
- 如何创建将保存指向函数的指针的队列
- 指针指向结构的指针(优先队列)
- 指针C++的优先级队列
- 矢量和指针队列数据交换:深层和浅层副本
- 将包含指向该类型队列的指针的结构推送到队列上时发生运行时崩溃