【问题标题】:C++ circular list error [closed]C ++循环列表错误[关闭]
【发布时间】:2014-08-23 20:42:43
【问题描述】:

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

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;
}

【问题讨论】:

    标签: c++ list iterator


    【解决方案1】:

    这部分是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();
    

    【讨论】:

    • 我认为第三行应该以else开头; else if(++i ...
    • 可以,但我选择不进行优化,因为最理想的情况是,一开始就不应该使用整个算法。
    • 感谢 mike 和 wimmel,我实施了您的更改,并对我的计数进行了一个小更改,并且效果很好
    • @MikeDeSimone 如果i == men.end() 你将执行i = men.begin(),然后执行++i
    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2023-03-07
    • 2017-01-30
    • 2012-12-18
    • 2012-12-09
    相关资源
    最近更新 更多