迭代器有效性,在 std::set 中的 erase() 调用之后
在 std::set invalidate iterator 中进行擦除调用吗?正如我在最后一行的第 5 名以下所做的那样..?如果是的话,从集合中删除所有元素的更好方法是什么
Do erase call in std::set invalidate iterator ? As i have done below 5th from last line..? if yes what is better way to erase all elements from set
class classA
{
public:
classA(){};
~classA(){};
};
struct structB
{
};
typedef std::set <classA*, structB> SETTYPE;
typedef std::map <int, SETTYPE>MAPTYPE;
int __cdecl wmain (int argc, wchar_t* pArgs[])
{
MAPTYPE mapObj;
/*
...
.. Some Operation Here
...
*/
for (MAPTYPE::iterator itr1=mapObj.begin(); itr1!=mapObj.end(); itr1++)
{
SETTYPE li=(*itr1).second;
for (SETTYPE::iterator itr2=li.begin();itr2!=li.end();itr2++)
{
classA *lt=(classA*)(*itr2);
li.erase(itr2);
delete lt; // Does it invalidate Iterator ?
}
}
}
推荐答案
既然你只是明显地删除了集合中的每个元素,你可以这样做:
Since you are just apparently deleting every element of the set, you could just do:
for (SETTYPE::iterator itr2=li.begin();itr2!=li.end();itr2++)
{
classA *lt=(classA*)(*itr2);
delete lt;
}
li.clear(); // clear the elements
相关文章