Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast an iterator of a vector of shared_ptr type

How can I cast an iterator of a vector of shared_ptr type? Consider following example:

typedef boost::shared_ptr < MyClass > type_myClass;

vector< type_myClass > vect;
vector< type_myClass >::iterator itr = vect.begin();

while(itr != vect.end())
{
   //Following statement works, but I wish to rather cast this 
   //to MyClass and then call a function?
   (*itr)->doSomething(); 
}
like image 372
Vijayendra Avatar asked Jun 26 '11 17:06

Vijayendra


2 Answers

You do not want to cast, but rather extract a reference to the object:

MyClass & obj = *(*it); // dereference iterator, dereference pointer
obj.doSomething();
like image 142
David Rodríguez - dribeas Avatar answered Oct 07 '22 07:10

David Rodríguez - dribeas


You can simply grab a reference by de-referencing it again.

MyClass& ref = **itr;

And then cast it or whatever however you'd like.

like image 34
Puppy Avatar answered Oct 07 '22 06:10

Puppy