Danny
Danny

Reputation: 33

Accessing a method of a class object stored in a vector using an Iterator. How?

Hey first question I'm asking here many thanks in advance. I'm using a vector to store a series of pointers to objects of a class CSquare, I want to have an iterator that I can pass around so that I can access the functions of a certain object. This is my current code to attempt this with no luck. IntteliSense telling me that there are 'No members Available'.

    vector <CSquare*> pSquares;
    //filled in vector
    vector<CSquare*>::iterator tempIt = pSquares.begin();
    tempIt->getName();

Not sure what else to add, but if you need anything else to help me out please say.

Again thanks a lot.

Edit: Problem solved, I had to dereference twice. The following code works, thought I'd just leave this up incase anyone else need the same help, thanks for looking anyway.

    vector <CSquare*> pSquares;
    //filled in vector
    vector<CSquare*>::iterator tempIt = pSquares.begin();
    (**tempIt).getName();

Upvotes: 3

Views: 2088

Answers (2)

You need an extra dereference:

(*tempIt)->getName();

The reason is that what you are storing inside the vector are pointers, so *tempIt is a reference to a pointer that you need to dereference again to access the CSquare object.

Upvotes: 4

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81694

Remember that you need to dereference the iterator to get the pointed-to thing. Because this is a vector<CSquare*>, your iterator is effectively a pointer-to-pointer-to-CSquare, so you need to do this:

(*tempIt)->getName();

Upvotes: 5

Related Questions