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

Efficiently remove last element from std::list

这似乎是一个简单的问题,当然是可行的,但我想高效地完成它。

Objective:
如果满足条件,则从 std::list 中移除最后一个元素。

问题:
我的编译器 (MSVC++ 10) 对于 std::list.erase() 的方法调用将反向迭代器转换为 const 迭代器不满意。消息是:

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;
    }
}

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

使用反向迭代器从双向列表中删除列表元素似乎是一件合理的事情。我在这里明显遗漏了什么吗?

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

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

修复代码中的特定错误Can I convert a reverse iterator to a forward iterator?

mylist.erase((pos+1).base()); 

使用std::reverse_iterator::base

The base iterator refers to the element that is next (from the std::reverse_iterator::iterator_type perspective) to the element the reverse_iterator is currently pointing to.

无论如何,pop_back 是您的最佳选择。