如何从向量中获得非const值

how to get a non-const value from a vector

本文关键字:const 向量      更新时间:2023-10-16

如果我有一个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