我有一个 Car 对象的 vector ,声明为
vector<Car> vCars
在我的一个函数中,我需要删除 vector 的第一个元素。听起来很简单吧?抛出错误的行:
vCars.erase( vCars.begin() );
错误:
no matching function for call to 'std::vector<Car>::erase(std::vector<Car>::const_iterator) const'
我知道 erase 通常只接受一个迭代器作为它的参数,而不是一个 const_iterator。我一直在寻找错误的解决方案或变通方法,例如 erase-remove 惯用语,但从我所看到的情况来看,当我需要按位置删除时,它只会按值删除一个元素——而且足够简单,只是第一个位置的元素! (我知道这对于 vector 来说不是很好的性能,但我需要为此使用 vector )
编辑:为了澄清情况,调用包含的函数如下:
/// 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
仅适用于 iterator
,它也适用于 C++11 中的 const_iterator
。毕竟,要调用删除,您需要一个对 vector 的可修改引用,如果有的话,您总是可以从 const
中得到一个普通的非 const iterator
.这就是为什么他们将成员更改为采用 const_iterator
的原因。
问题是,如果您调用它的对象也是 const
,您只能从 begin()
返回一个 const_iterator
合格 - 在这种情况下,您的 vCars
。反过来,这意味着您只能对其调用 const
限定的函数,这是编译器尝试的:
... call to 'std::vector::erase(std::vector::const_iterator) const' ^^^^^
我认为您同意 erase
被 const
限定是没有意义的。 :)
关于c++ - 删除使用 const_iterator 的 vector 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12662636/