【问题标题】:c++ erase in a stl list of listsc ++擦除列表的stl列表
【发布时间】:2014-12-21 08:20:29
【问题描述】:

我想使用 stl 做一个列表列表,但是当我尝试查找一个元素并将其从列表中删除时遇到问题,我无法找出错误。

我用随机数做了一个小例子:

int main(int argc, char** argv) {

list<list <int> > l;
srand ( time(NULL) );

list<list <int> >::iterator j;
list<int>::iterator i;
for(int n1=0;n1<10;n1++){
    list<int> aux;
    int r=rand()%10 +1;
    for(int n=0;n<r;n++){
        int r2=rand()%100;
        aux.push_back(r2);
    }
    l.push_back(aux);
}
for(j=l.begin();j!=l.end();j++){
    list<int> l2=(*j);
    for(i=l2.begin();i!=l2.end();i++)
        cout << (*i) << " -> ";
    cout << endl;
}
int num;
cout << "element to delete: ";
cin >> num;

// ===== 问题应该在这里=====

for(j=l.begin();j!=l.end();j++){
    for(i=(*j).begin();i!=(*j).end();i++){
        if((*i)==num){
            (*j).erase(i);
        }
    }
}

//====================================

cout << endl;
for(j=l.begin();j!=l.end();j++){
    list<int> l2=(*j);
    for(i=l2.begin();i!=l2.end();i++)
        cout << (*i) << " -> ";
    cout << endl;
}

}

非常感谢您提供的任何帮助。

【问题讨论】:

  • 您需要告诉我们问题所在。

标签: c++ list search insert


【解决方案1】:

你可能是对的:那个循环很可能是问题所在。

这是因为您在迭代 *j 的同时擦除它;删除该元素将使其迭代器无效。

Here is how to erase from a list whilst iterating over it.

顺便说一句,您的代码很难阅读。

【讨论】:

  • 非常感谢,我找到了问题所在。我想我不得不搜索更多。 (*j).erase(i++);
  • @Kaekh 我不知道那个解决方案。它不会在当前节点之后跳过测试节点吗?即,如果您的内部列表连续有两个值要删除,您的解决方案只会删除第一个。
  • @Kaekh:请确保您正确实施了链接解决方案:您需要在 for 循环定义中摆脱原来的 i++,并引入 else 子句。
  • @LightnessRacesinOrbit 试试这个:std::list&lt;int&gt; lst {1,2,7,7,3,4,7,7,5}; for (auto i = lst.begin(); i != lst.end(); i++) if (*i == 7) lst.erase(i++);
  • 内部需要更像这样:if (*i == num) i=lst.erase(i); else i++;(当然,从 for 循环中删除了增量。)
猜你喜欢
  • 2011-04-21
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 2017-11-17
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多