Search code examples
c++vectorstliteratordereference

Iterator Dereferencing


I am using a vector in c++,

vector<Agents> agentlist;

Why does this work,

(agentlist.begin() )->print();

and this not?

*(agentlist.begin() ).print();

Isn't it valid to dereference an iterator using *?


Solution

  • See operator Precedence, . has higher precedence than *

    *(agentlist.begin()).print();
    

    represents as:

    *((agentlist.begin()).print());
    

    While iterator has no .print() function call, compiler will throw out compile error.

    You need:

     agentlist.begin()->print();  or  (*agentlist.begin()).print();