1

我一直在处理约瑟夫斯问题(作业的另一部分),我们应该做的是给两个变量mn. m代表它开始的玩家,n代表玩家的数量。我在弄清楚将m变量放在哪里时遇到问题,以便程序在正确的播放器上启动并跳过适当数量的空格。

因此,如果m是 2 并且有 6 个玩家,它将从玩家 2 开始,传给玩家 3,消除玩家 3 并转到玩家 4,传给玩家 5 并消除他们,依此类推,直到剩下一名玩家。这是我希望得到的输出:

Enter M and N: 2 6

Person removed: 3
Person removed: 6
Person removed: 4
Person removed: 2
Person removed: 5

*** AND THE WINNER IS 1!! ***

相反,使用我拥有的代码,我得到

Person removed: 2
Person removed: 4
Person removed: 6 
Expression: list iterator not incrementable

int i = 1; i <= n; i++我有用 , 替换的想法,int i = m; i <= n; i++i正确的数字开始,但这给了我:

Player removed: 3
Player removed: 5
Player removed: 2
Player removed: 6
*** AND THE WINNER IS 4!! ***

我也知道为什么它只增加了 5 名玩家,但我不确定m可以去哪里添加正确数量的玩家。任何想法/提示将不胜感激。

#include <iostream>
#include <list>

using namespace std;

int main() {
    int m, n;
    cout << "Enter M and N: ";
    cin >> m;
    cin >> n;
    list<int> players;
    for (int i = 1; i <= n; i++) {
        players.push_back(i); // adding players to the list
    }
    list<int>::iterator it = players.begin();
    while (players.size() > 1) {
        it++;
        if (it == players.end()) { // if the iterator reaches the end of the list
            it = players.begin();  // wrap around to beginning
        }
        cout << "Person removed: " << *it << endl;
        it = players.erase(it);
        if (players.size() == 1) {
            cout << "*** AND THE WINNER IS " << players.front() << "!! ***" << endl;
        }
    }

    system("pause");
    return 0;
}
4

0 回答 0