其他分享
首页 > 其他分享> > c – 在循环中使用迭代器删除unordered_set中的元素

c – 在循环中使用迭代器删除unordered_set中的元素

作者:互联网

请考虑以下代码:

MyClass类是一个自定义类:

class MyClass
{
public:
    MyClass(int v) : Val(v) {}
    int Val;
};

然后,下面的代码将在调用它之后导致循环中的Debug Assertion失败= T.erase(it);:

unordered_set<MyClass*> T;
unordered_set<MyClass*>::iterator it;

for (int i=0; i<10; i++)
    T.insert(new MyClass(i));

for (it = T.begin(); it != T.end(); it++)
{
    if ( (*it)->Val == 5 )
        it = T.erase(it); // After this line executes, in the next loop, the error occurs.
}

如何解决它和为什么?
PS:我的环境:VS2010

解决方法:

假设最后一个元素的Val = 5.

它= T.erase(it)被调用,它被设置为T.end().

然后调用它,这会导致错误,因为它已经设置为结束.

基本上……当你擦除当前代码中的元素时,最终会使迭代器双倍前进.

你可以选择这样的东西……

for (it = T.begin(); it != T.end(); (*it)->Val == 5? it = T.erase(it) : ++it)
  ;

标签:unordered-set,c
来源: https://codeday.me/bug/20190830/1771195.html