我有一个 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'
我知道擦除通常只采用迭代器作为其参数,而不是 const_iterator。我一直在寻找错误的解决方案或变通方法,例如删除删除习惯用法,但从我所看到的来看,当我需要按位置删除时,它只会按值删除元素 - 并且足够简单,只是第一个位置的元素! (我知道这对于 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
仅适用于迭代器,也适用于 C++11 中的 const_iterator。毕竟,要调用删除,您需要对 vector 的可修改引用,如果有的话,您总是可以从 const
迭代器获得一个普通的非常量 迭代器
。这就是他们将成员更改为采用 const_iterator
的基本原理。
问题是,如果您调用它的对象也是 const
,您只能从 begin()
返回一个 const_iterator
合格 - 在本例中为您的 vCar
。反过来,这意味着您只能在其上调用 const
限定函数,这是编译器尝试的:
... call to 'std::vector::erase(std::vector::const_iterator) const' ^^^^^
我认为您同意 erase
被 const
限定是没有意义的。 :)
关于c++ - 删除使用 const_iterator 的 vector 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12662636/