user3748682
user3748682

Reputation: 93

how to get a non-const value from a vector

If I have a class:

class T{
  public:
     int Id;
  //some methods, constructor..
}

and in other class:

vector<T> collection;

and want to a write a method:

T& getValue(int Id){
   //scanning the vector till i find the right value
 }

The problem is that scanning the vector through iterator always give a const value so I get an error about qualifiers. So how do I get a value from a vector? but Not a const one.

EDIT: According to the Answers I tried to so something like this:

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
}

the definition of groups: vector groups;

This is exactly the same example I gave at first but now T is Group.

Upvotes: 1

Views: 1315

Answers (1)

Mike DeSimone
Mike DeSimone

Reputation: 42805

The following code should give you a non-const iterator and work fine:

for(vector<T>::iterator i = collection.begin(); 
    i != collection.end(); ++i) {
    if(Id != i->Id)
        continue;
    // Matching ID! do something with *i here...
    break;
}

If this doesn't help, please explain in more detail what is broken.


The problem here is the const in your declaration:

Group& Server::findGroup(unsigned int userId) const //<==THIS

That means that this is a const Server*, and thus everything in it is const as well, including groups. Which means that groups.begin() will return a const_iterator instead of an iterator.

One thing you can do (might not be a good idea; you need to be really sure!) would be to mark groups as mutable, which lets it be changed even if its enclosing object is const:

mutable vector<T> groups;

Doing this will make groups.begin() return a regular iterator.

But I would instead ask you to reevaluate why this method is declared const at all, since you're returning part of the object in a form that can be changed and thus you're not really honoring const.

Upvotes: 3

Related Questions