擦除使用const_iterator的向量的元素

Erasing an element of a vector that uses const_iterator

本文关键字:向量 元素 iterator const 擦除      更新时间:2023-10-16

我有一个Car对象的向量,声明为

vector<Car> vCars

在我的一个函数中,我需要擦除向量的第一个元素。听起来很简单,对吧?抛出错误的行:

vCars.erase( vCars.begin() );

错误:

no matching function for call to 'std::vector<Car>::erase(std::vector<Car>::const_iterator) const'

我知道擦除通常只使用迭代器作为参数,而不使用const_iterator。我一直在寻找错误的解决方案或变通方法,比如擦除-删除习惯用法,但据我所见,当我需要按位置删除时,它只按值删除元素——简单地说,只删除第一个位置的元素!(我知道这对于矢量来说不是很好的性能,但我需要使用矢量)

编辑:为了澄清情况,调用包含的函数如下:

/// Removes the Car at the front of the garage without returning the instance.
void Garage::pop() const {
if ( !empty() ) {
vCars.erase( vCars.begin() );
}
}

编辑:我现在明白我哪里错了。有很多方法都是const方法,我只是无意中把pop()变成了const方法!一旦我去掉const,问题就解决了。谢谢你指引我正确的方向!

这并不是说erase只适用于iterators,它也适用于C++11中的const_iterators。毕竟,要调用擦除,您需要一个对向量的可修改引用,如果您有,您总是可以从const中获得一个普通的非常数iterator。这就是他们为什么将成员改为const_iterator的理由。

问题是,只有当您调用的对象也是const限定的(在本例中是您的vCars)时,您才能从begin()返回const_iterator。反过来,这意味着你只能在上面调用const限定的函数,这就是编译器所尝试的:

。。。调用"std::vector::erase(std::vector::const_iterator)const"^^^^^

我想你同意eraseconst合格是没有意义的。:)

错误消息:

没有用于调用"std::vector::erase(std::vector::const_iterator)const"的匹配函数

意味着vCars.begin()产生一个const_iterator,这反过来意味着vCars是一个常量对象或引用。不允许通过该引用修改矢量。如果函数需要修改向量,则不能使用常量引用。

请注意,在声明为const的成员函数中,隐式this指针的类型为T const *(即,不能在const函数中修改对象)。如果是这种情况,则需要从函数中删除const限定符。

您的参数"vCars"似乎是对向量的常量引用。您可以通过const_cast使其可变,或者更改您的函数设计。