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;
}
但是,此示例代码不起作用,因为it
是反向迭代器而erase()
不将反向迭代器作为其参数。
如何修改此代码以使其有效?
答案 0 :(得分:6)
你可以使用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
来完成此操作
答案 1 :(得分:5)
我会通过不使用反向迭代器来解决问题。我可能会写这样的东西:
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;
}
答案 2 :(得分:4)
好的,你有几个选择 - 你从最后删除 - 所以你可以:
resize()
if (MyVector.size() > 3)
MyVector.resize(MyVector.size() - 3);
else
MyVector.clear(); // presumably you don't want all anyway!
简单差异
if (MyVector.size() > 3)
MyVector.erase(MyVector.end() - 3, MyVector.end());
else
MyVector.clear(); // presumably you don't want all anyway!
你采取的方法并不是非常惯用的
答案 3 :(得分:3)
如果您只想删除背面的N个元素:
size_t N = 3;
size_t to_remove = std::min(vec.size(), N);
vec.erase(vec.end() - to_remove, vec.end());
答案 4 :(得分:1)
您无法将const_iterator
或const_reverse_iterator
传递给erase()
,因为它是只读迭代器!
您应该使用非const 转发迭代器版本:std::vector<int>::iterator
。