hkB*_*sai 2 c++ iterator vector erase
std::vector::erase()不接受反向迭代器.
有没有办法用反向迭代器调用这个方法?
我的示例代码是:
std::vector<int> MyVector;
for (int i=0; i<10; i++)
{
MyVector.push_back(i);
}
// Now suppose that I want to erase the last three elements
int nEraseCount = 0;
for (std::vector<int>::const_reverse_iterator it=MyVector.rbegin();
it<MyVector.rend(); ++it)
{
MyVector.erase(it);
if (++nEraseCount == 3) break;
}
Run Code Online (Sandbox Code Playgroud)
但是,此示例代码不起作用,因为it它是反向迭代器,erase()并且不将反向迭代器作为其参数.
如何修改此代码以使其有效?
您可以使用base()从reverse_iterators转换为迭代器,尽管您需要减去一个以获得指向同一元素的那个,因此rbegin()指向end()和rend()指向begin()(因为它不是在现实中可能指向一个).
你有更多的问题,因为你使用的const_reverse_iterator不能转换为非const的,而erase需要非const迭代器.逻辑是您正在修改集合,因此您使用非const迭代器.
在你的情况下,你的循环有一个更大的问题,因为你正在删除迭代器,从而使它们无效,然后尝试移回到前一个元素.
如果你需要删除最后3个元素,那么你应该使用一个擦除方法,它取一个范围而不是一次删除一个.
MyVector.erase(MyVector.rbegin() + 3).base(), MyVector.end() )只要您知道这一点,就可以在这种特殊情况下使用MyVector.size() >= 3
我会通过不使用反向迭代器解决问题.我可能会写这样的东西:
std::vector<int> MyVector;
for (int i=0; i<10; i++)
{
MyVector.push_back(i);
}
// Now suppose that I want to erase the last three elements
int nEraseCount = 0;
while (nEraseCount < 3 && !MyVector.empty())
{
MyVector.pop_back();
++nEraseCount;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2652 次 |
| 最近记录: |