问题描述
我有对象的列表。我从该列表中获取一些项目,并做项目的东西。如果工作没有错误,我希望从列表中删除这些项目。之后,在擦除我得到异常的不兼容的迭代器。我明白tmp是不同的列表。但是如何解决这个问题呢?
I have list with objects. I get some items from that list and do something with items. If work is done without errors i wish to delete these items from list. After that, on erase I get exception of incompatible iterator. I understand that tmp is different list. But how to solve this problem?
#include <list>
class A
{
public:
A(int i):i_(i){}
private:
int i_;
};
int _tmain(int argc, _TCHAR* argv[])
{
std::list<A> list;
A a(1), b(2), c(3);
list.push_back(a);
list.push_back(b);
list.push_back(c);
std::list<A> tmp;
tmp.insert(tmp.end(), list.begin(), list.end());
// do something with tmp
// if all is ok, then erase what is done
list.erase(tmp.begin(), tmp.end());
return 0;
}
tmp.Insert
不总是充满列表
。它可以复制 list
的一部分,所以我不想清除整个列表
。
tmp.Insert
not always get full list
. It can copy part of list
, so i don't want clear whole list
.
推荐答案
不能使用另一个列表中的迭代器从一个列表中删除。迭代器指向列表中的某个节点。它指向特定列表中的 。当你把这些东西复制到另一个列表,你有两个列表,两个节点现在。
You can't erase from one list using iterators from another list. An iterator "points" to some node in a list. Its pointing to something in a specific list. When you copy those things into another list, you have two lists with two sets of nodes now. Your iterator points to only one of those copies, not to both.
在程序中, std :: list
析构函数会导致你的列表清理,所以你甚至不需要做一个明确的清除。
In the program as it is, the std::list
destructor will cause your list to cleanup, so you don't even need to do an explicit clear.
像其他人说的,你可以使用以清除列表中的内容。但我不是100%肯定那是你的意思。你的意思是擦除列表中的所有内容,也在tmp?如果是这种情况,您可以使用使用谓词
As others have said, you can use clear to blow away the contents of the list. But I'm not 100% sure thats what you mean to do. Do you mean to erase all the contents of list that are also in tmp? If that's the case, then you may wish to use remove_if with a predicate
class CIsContainedInOtherList
{
private:
const std::list<int>& m_list;
public:
CIsContainedInOtherList(const std::list<int>& list);
// return true if val is in m_list
bool operator()(const int& val) const
{
std::list<int>::const_iterator iter
= std::find(m_list.begin(), m_list.end(), val);
return (iter != m_list.end())
}
}
int main()
{
...
CIsContainedInOtherList ifInOtherList(tmp);
std::list<int>::iterator iter =
remove_if(list.begin(), list.end(), ifInOtherList);
// remove everything that matched the predicate
list.erase(iter, list.end());
}
这篇关于std :: list erase不兼容迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!