C++ 列表迭代器擦除";“调试断言失败”;

C++ 列表迭代器擦除";“调试断言失败”;,c++,list,iterator,C++,List,Iterator,我有两个std::列表。我想删除列表1中的所有项目,并将其插入第二个项目,反之亦然。我的代码不工作(获取访问冲突和“列表迭代器不可取消引用”) for(std::list::iterator it=list1.begin();it!=list1.end();+it){ 它=列表1。擦除(它); 列表2.将_向后推(*it); } it=list1.begin(); 它=列表2.擦除(它);//因为在上面的循环中最后一个元素没有被删除 列表2.将_向后推(*it); 第二种方法的对称代码。我一次

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

for(std::list::iterator it=list1.begin();it!=list1.end();+it){
它=列表1。擦除(它);
列表2.将_向后推(*it);
}
it=list1.begin();
它=列表2.擦除(它);//因为在上面的循环中最后一个元素没有被删除
列表2.将_向后推(*it);
第二种方法的对称代码。我一次设法在两个列表之间传输项目,但下一次我得到了错误


有什么帮助吗?

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

list1.swap(list2);

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

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

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. 
}
for(std::list::iterator it=list1.begin();it!=list1.end();+it){
it=list1.erase(it);//这有效地擦除并销毁了它,
//和erase()将迭代器返回到下一个元素。
//现在它=它+1
list2.push_back(*it);//复制下一个元素!!
//这里是我们有效地获得“for”的++it的地方。
//当“it”位于end()-1时使用擦除时,擦除返回end()
//尝试这样做=end()+1可能是由断言检测到的错误。
}

如果
list1
最初有偶数个元素,例如0,1,2,3,4,5,6,7,8,9,迭代器
end()
将指向不存在的10,您不需要(不能)擦除。此“
for
”将删除偶数元素(0,2,4,6,8),并将奇数元素(1,3,5,7,9)复制到
list2
。但是如果最初的
list1
有奇数元素,例如0,1,2,3,4,5,6,7,8,最后删除的元素是8,
erase
将迭代器返回到不存在的9=
end(),
,并且“for”尝试使用不传递断言来递增它。

std::swap(list1,list2)
?@Johnsyweb
std::list::swap
成员函数保证为常数时间。它应该只涉及交换两个指针(在C++11中可能还有一个大小数据成员)。@juanchopanza:那当然更好。
std::swap
函数的性能仍然会比当前的实现更好:)这是我得到的最快、最好的答案。
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. 
}