如何从向量中获得非const值
how to get a non-const value from a vector
如果我有一个class:
class T{
public:
int Id;
//some methods, constructor..
}
和其他类:
vector<T> collection;
并且想写一个方法:
T& getValue(int Id){
//scanning the vector till i find the right value
}
问题是通过迭代器扫描向量总是给出一个const值,所以我得到一个关于限定符的错误。那么如何从向量中得到一个值呢?但不是const。
编辑:根据答案,我试着这样做:
Group& Server::findGroup(unsigned int userId) const{
for(auto iterator=groups.begin();iterator!=groups.end();++iterator){
if(iterator->isInGroup(userId)){
return (*iterator);
}
}
//throw exception here
}
组的定义:向量组;
这和我一开始举的例子是一样的,但是现在T是Group
下面的代码应该会给你一个非const
迭代器,并且工作良好:
for(vector<T>::iterator i = collection.begin();
i != collection.end(); ++i) {
if(Id != i->Id)
continue;
// Matching ID! do something with *i here...
break;
}
如果这没有帮助,请解释更详细的是什么坏了
这里的问题是你的声明中的const
:
Group& Server::findGroup(unsigned int userId) const //<==THIS
这意味着this
是一个const Server*
,因此它的所有东西都是const
,包括groups
。这意味着groups.begin()
将返回const_iterator
而不是iterator
。
你可以做的一件事(可能不是一个好主意;将groups
标记为mutable
,即使它的封闭对象是const
:
mutable vector<T> groups;
这样做将使groups.begin()
返回一个常规的iterator
。
但是我反而会要求您重新评估为什么这个方法被声明为const
,因为您以可以更改的形式返回对象的一部分,因此您没有真正遵守const
。
相关文章:
- 如何在旧c++中初始化const-std向量
- 如何在 c++ 中将向量转换为<string>常量字符* const*?
- 如何在字符串向量中指向const int
- 索引 2D 向量时'Reference to type const..'编译错误
- STL按客户"<"运算符对向量进行排序。为什么要将"<"运算符定义为 const?
- 是否可以交换在 c++ 中作为函数 func(say) 中的参数传递的 const 向量的两个元素,例如:vector<int>func (const vector<int>&
- 在lambda中捕获各种向量使元素const
- 正确的方法通过巨大的const对象的向量
- 将共享_ptr的向量转换为shared_ptr的向量到const
- 通过const Rerefence传递向量并将元素添加到向量
- 与const成员配对的向量
- 将指向const的指针存储到structs的向量中
- 返回指向 const 对象的 const 共享指针的 const 向量
- 指向C样式数组元素的指针的const向量
- 如何对const向量排序?
- 非Const对象的Const向量
- 返回const对象的const向量的const向量
- 如何使用c++ 11初始化函数结果的const向量?
- 将非常量向量传递给引用<string> const 向量<const string>?
- 在类构造函数中初始化const向量(c++)