首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >列表迭代器擦除"Debug assertion failed“

列表迭代器擦除"Debug assertion failed“
EN

Stack Overflow用户
提问于 2013-02-11 07:31:34
回答 2查看 314关注 0票数 1

我有两个std::列表。我想删除列表1中的所有项目,并将其插入到列表2中,反之亦然。我的代码不工作(得到访问冲突和“列表迭代器不可解引用”)

代码语言:javascript
复制
for ( std::list<Item *>::iterator it = list1.begin(); it != list1.end(); ++it ) {
        it = list1.erase( it ); 
        list2.push_back( *it ); 
    }
it = list1.begin();
it = list2.erase( it ); // because the last element is not deleted in the above loop
list2.push_back( *it ); 

第二种方法的对称代码。我成功地在两个列表之间传输了一次条目,但下一次我就得到了错误。

有什么帮助吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-11 07:35:14

这可以通过std::listswap成员函数轻松高效地完成:

代码语言:javascript
复制
list1.swap(list2);

这具有恒定的时间复杂度。

票数 3
EN

Stack Overflow用户

发布于 2013-02-11 08:53:28

当然,您必须使用list::swap。但是您的代码显示您有一些误解。

代码语言:javascript
复制
for ( std::list<Item *>::iterator it = list1.begin(); it != list1.end(); ++it ) {
   it = list1.erase( it ); // this effectively erase and destroy *it, 
                 // and erase() return an iterator to the NEXT element. 
                 // Now it=it+1
   list2.push_back( *it ); // you copy the NEXT element!!  
   // here is where we efectively get the ++it of the 'for'. 
   // When erase was used when ‘it’ was at end()-1, erase return end()
   // The attempt to do it=end()+1 is an error probably detected by an assertion. 
}

如果list1最初有偶数个元素,例如0,1,2,3,4,5,6,7,8,9,迭代器end()将指向不存在的10,并且不需要擦除(铁路超高)。这个‘for’将删除偶数元素(0,2,4,6,8),并复制到list2 (1,3,5,7,9)。但是如果最初的list1有奇数元素,例如0,1,2,3,4,5,6,7, 8,最后删除的是8,erase返回一个迭代器到不存在的9= end(),,并且‘list1’尝试递增它,而不传递断言。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14803905

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档