<list> retreving items problem with iterator
I have a list of type Instruction*. Instruction is a class that I made. This class has a function call开发者_运维问答ed execute().
I create a list of Instruction*
list<Instruction*> instList;
I create an Instruction*
Instruction* instPtr;
instPtr = new Instruction("test",10);
If I call
instPtr.execute();
the function will be executed correctly, however if I store instPtr in the instList I cannot call the execute() function anymore from the list.
//add to list
instList.push_back(instPtr);
//create iterator for list
list<Instruction*>::iterator p = instList.begin();
//now p should be the first element in the list
//if I try to call execute() function it will not work
p -> execute();
I get the following error:
error: request for member ‘execute’ in ‘* p.std::_List_iterator<_Tp>::operator-> [with _Tp = Instruction*]()’, which is of non-class type ‘Instruction*’
p
is an iterator of Instruction *
pointers. You can think of it as if it were of type Instruction **
. You need to double dereference p
like so:
(*p)->execute();
*p
will evaluate to an Instruction *
, and further applying the ->
operator on that will dereference the pointer.
try (*p)->execute();
Instead of p->execute() you need (*p)->execute();
You need to de-reference the list iterator to get the value associated with the node in the list referenced by your iterator.
The best solution is keep boost::shared_ptr in your list. Remember all STL containers working with copy principle.
Use this code
list > instList;
then call your execute function as usual
instList[i]->execute();
as you can see you call execute as you keep pointers in your list. this is the best solution
精彩评论