为什么我的代码对除一个实例之外的所有内容都有效?

问题描述 投票:0回答:1

我在 C++ 实验室做作业,我需要从键盘获取一个数字,并在 STL 列表中输入数字后删除一个元素。由于某种原因,如果我将 7 个元素放入列表中,恰好是 {1,2,2,3,4,2,5} 并且 ellement 是 2,则它输出 {1,2,2,2} 而不是 {1,2, 2,4,2}。为什么?

#include <iostream>
#include <iterator>
#include <list>
using namespace std;
list<int> STL_MyList(std::list<int> g, int n);
int main()
{
    int s, d;
    list<int>::iterator it;
    cout<<"Enter how many elements you want in the list?"<<endl;
    cin>>s;
    cout<<"Start now: "<<endl;
    cin>>d;
    list<int> list1{d};
    for (int i = 0; i < s-1; ++i) {
        cin>>d;
        list1.push_back(d);
    }
    for (auto i : list1) {
        cout << i << ' ';
    }
    cout<<endl<<"After what number do you want to delete element?"<<endl;
    cin>>s;
    list1.operator=(STL_MyList(list1, s));
    cout<<"Result:"<<endl;
    for (auto i : list1) {
        cout << i << ' ';
    }
    cout<<endl<<"Do you want to do it again? (Yes - 1 / No - 0)"<<endl;
    cin>>s;
    if (s){
        main();
    } else{
        cout<<"Finish.";
    }

    return 0;
}

//Delete element after n in STL list
list<int> STL_MyList(list<int> g, int n){
    auto itr = g.begin();
    int a=n-1;
    for (itr = g.begin(); itr != g.end(); ++itr){
        if (*itr!=n && a==n)
        {
            itr=g.erase(itr);
        }
        a=*itr;
    }
    return g;
}

我尝试更改其背后的代码和逻辑 - 但这一切都导致了很多错误,并且整个代码都出了问题。

c++ list function stl
1个回答
0
投票

所以...我已经通过一步步调试弄清楚了 问题是迭代器经过了列表的

end()
两次。 我已经解决了一个问题,并且我的代码现在可以正常工作,我只需要添加
break;
,这样它就不会超出所述列表的范围。还将其放入
while
循环中,并重命名一个函数来表示它正在做什么。 谢谢大家的帮助。

#include <iostream>
#include <list>
using namespace std;
list<int> DeleteElementAfterValue(std::list<int> g, int n);
int main()
{
    int s=1, d;
    while (s){
    list<int>::iterator it;
    cout<<"Enter how many elements you want in the list?"<<endl;
    cin>>s;
    cout<<"Start now: "<<endl;
    cin>>d;
    list<int> list1{d};
    for (int i = 0; i < s-1; ++i) {
        cin>>d;
        list1.push_back(d);
    }
    for (auto i : list1) {
        cout << i << ' ';
    }
    cout<<endl<<"After what number do you want to delete element?"<<endl;
    cin>>s;
    list1.operator=(DeleteElementAfterValue(list1, s));
    cout<<"Result:"<<endl;
    for (auto i : list1) {
        cout << i << ' ';
    }
    cout<<endl<<"Do you want to do it again? (Yes - 1 / No - 0)"<<endl;
    cin>>s;
    }
    cout<<"Finish.";
    return 0;
}

//Delete element after n in STL list
list<int> DeleteElementAfterValue(list<int> g, int n){
    auto itr = g.begin();
    int a=n-1;
    for (itr = g.begin(); itr != g.end(); ++itr){
        if (*itr!=n && a==n)
        {
            itr=g.erase(itr);
        }
        if (itr != g.end()) {
            a = *itr;
        }
        else{
            break;
        }
    }
    return g;
}
© www.soinside.com 2019 - 2024. All rights reserved.