高效地从 std::list 中删除最后一个元素

8
这似乎是一个简单的问题,当然可以做到,但我希望能够高效地完成。 目标:
如果满足某个条件,则从std::list中删除最后一个元素。 问题:
我的编译器(MSVC++ 10)不喜欢将反向迭代器强制转换为const迭代器以调用std::list.erase()方法。消息如下:
error C2664: 'std::_List_iterator<_Mylist>
 std::list<_Ty>::erase(std::_List_const_iterator<_Mylist>)' : cannot
 convert parameter 1 from 'std::reverse_iterator<_RanIt>' to
 'std::_List_const_iterator<_Mylist>'

我尝试过的代码:

std::list<mytype> mylist;

// lots of code omitted for clarity
bool ends_badly = true;

while(ends_badly && mylist.size() > 0)
{
    auto pos = mylist.crbegin(); // Last element in the list
    if ((*pos)->Type() == unwanted)
    {
        mylist.erase(pos); // Here is where the compiler complains
    }
    else
    {
        ends_badly = false;
    }
}

我可以通过使用前向迭代器并循环遍历列表到末尾来解决这个问题,但那太麻烦了。编译器在此上下文中可以接受前向迭代器,我尝试将反向迭代器强制转换为常量迭代器,但编译器也不喜欢。

在双向链表中使用反向迭代器删除列表元素似乎是合理的事情。这里有什么明显的问题吗?


你可以在反向迭代器上调用 base(),但是你需要自己注意正确的偏移量。 - Kerrek SB
5
我可能没有理解其中的内涵,但为什么不使用 pop_back 函数呢?(链接指向 http://en.cppreference.com/w/cpp/container/list/pop_back) - user4581301
除了@user4581301所说的,您还可以使用remove_ifback迭代器。 - Brad Allred
如果您需要修改列表,为什么要使用const迭代器? - Brad Allred
2
就此而言,“ForwardIterator”有其含义,而不是“不是反向迭代器的迭代器”。 - Ben Voigt
显示剩余3条评论
2个回答

8

我认为您可以通过以下方式简化代码片段:

while (!mylist.empty() && mylist.back()->Type() == unwanted) {
    mylist.pop_back();
}

2
mylist.back()->Type() == unwanted 更简单。 - SirGuy

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接