我有两个std::列表。我想删除列表1中的所有项目,并将其插入到列表2中,反之亦然。我的代码不工作(得到访问冲突和“列表迭代器不可解引用”)
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 ); 第二种方法的对称代码。我成功地在两个列表之间传输了一次条目,但下一次我就得到了错误。
有什么帮助吗?
发布于 2013-02-11 07:35:14
这可以通过std::list的swap成员函数轻松高效地完成:
list1.swap(list2);这具有恒定的时间复杂度。
发布于 2013-02-11 08:53:28
当然,您必须使用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.
}如果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’尝试递增它,而不传递断言。
https://stackoverflow.com/questions/14803905
复制相似问题