c++循环列表错误

C++ circular list error

本文关键字:错误 列表 循环 c++      更新时间:2023-10-16

我正在创建一个程序,它将获取n个项目的列表,然后消除每三个项目,直到只剩下一个。我得到一个错误,我的代码正在访问一个不存在的列表项。我知道我可以使用整数计数器来修改它但我更希望找到问题的根源

int main()
{
    double suitors=0;
    int checker=0;
    int temp=0;
    do
    {
        cout << "How many suitors are there, min of 4 n";
        cin >> suitors ;
        checker=suitors;
        if (cin.fail()||checker!=suitors||suitors<4)
        {
            cout << "You have entered an invalid input.n";
            cin.clear();
            cin.ignore(100, 'n');
            suitors=-1;
        }
    }
    while (checker!=suitors||suitors<4);
    list<int> men;  
    for (int j=1; j<=suitors; j++)
    {
        men.push_back(j);
    }
    list<int>::iterator i;
    i=men.begin();
    for (int j=1; j<suitors;j++)
    {
        temp=0;
        while (temp<3)
        {
            temp=temp+1;
            if (temp==3)
            {
                cout << "Suitor #" << *i << " is eliminated n";
                i=men.erase(i);
                break;
            }
            if (i!=men.end())
            {
                i++;
            }
            else //this is trying to reset the iterator to the start when it hits the end
            {
                i=men.begin();
            }
        }
    }
    i=men.begin();
    cout << "If there are " << suitors 
    << " then the winner will be suitors #" << *i << endl;
    return 0;
}

这部分是bug:

if (i!=men.end())
{
    i++;
}
else //this is trying to reset the iterator to the start when it hits the end
{
    i=men.begin();
}

如果i指向列表的最后一项,它将走i != men.end()路线,执行++i,然后在下一次循环中执行i == men.end()

正确的代码是:

if(i == men.end())
    i = men.begin();
if(++i == men.end())
    i = men.begin();