擦除使用const_iterator的向量的元素
Erasing an element of a vector that uses const_iterator
我有一个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
只适用于iterator
s,它也适用于C++11中的const_iterator
s。毕竟,要调用擦除,您需要一个对向量的可修改引用,如果您有,您总是可以从const
中获得一个普通的非常数iterator
。这就是他们为什么将成员改为const_iterator
的理由。
问题是,只有当您调用的对象也是const
限定的(在本例中是您的vCars
)时,您才能从begin()
返回const_iterator
。反过来,这意味着你只能在上面调用const
限定的函数,这就是编译器所尝试的:
。。。调用"std::vector::erase(std::vector::const_iterator)const"^^^^^
我想你同意erase
被const
合格是没有意义的。:)
错误消息:
没有用于调用"std::vector::erase(std::vector::const_iterator)const"的匹配函数
意味着vCars.begin()
产生一个const_iterator
,这反过来意味着vCars
是一个常量对象或引用。不允许通过该引用修改矢量。如果函数需要修改向量,则不能使用常量引用。
请注意,在声明为const
的成员函数中,隐式this
指针的类型为T const *
(即,不能在const函数中修改对象)。如果是这种情况,则需要从函数中删除const
限定符。
您的参数"vCars"似乎是对向量的常量引用。您可以通过const_cast使其可变,或者更改您的函数设计。
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 在 C++ 中输出枚举类类型的向量元素
- 用向量的向量元素初始化向量的空向量
- 为什么不允许使用可变长度数组作为向量元素?
- 在函数中传递向量元素
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 返回向量元素的 l 值的正确方法是什么?
- 当向量增长时,指向向量元素的C++指针是否无效
- 如何在C++中从一个向量元素减去std::unorderede_map向量元素并更新它
- C++:向量元素赋值导致访问冲突
- 将向量元素与字符串元素进行比较,而不初始化向量
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 使用递归C++向量元素的总和
- 如何查找为数组中的最低值编制索引的向量元素
- 限制指针访问STL ::向量元素
- 访问索引指向向量元素时的seg故障 - 做错了什么
- 如何使用指针访问向量元素的各个元素
- 向量元素数据损坏了Find()操作
- 将字符值分配给向量元素.C