这似乎是一个简单的问题,当然可以做到,但我希望能够高效地完成。
目标:
如果满足某个条件,则从std::list中删除最后一个元素。 问题:
我的编译器(MSVC++ 10)不喜欢将反向迭代器强制转换为const迭代器以调用std::list.erase()方法。消息如下:
如果满足某个条件,则从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 SBpop_back
函数呢?(链接指向 http://en.cppreference.com/w/cpp/container/list/pop_back) - user4581301remove_if
和back
迭代器。 - Brad Allred