Matthew
Matthew

Reputation: 461

Accessing Vector of Pointers?

I'm trying to get a simple bit of code to work. I have a function called 'get_object_radius' which searches an area for instances of 'Creature', and pushes their pointers to a vector, then returns the vector.

I then want to cycle through them all and display their names from outside the function. I'm pretty sure I'm adding them to the vector correctly, but I'm not cycling through the vector of pointers correctly, am I?

Here's the relevant code snippet (that doesn't work):

//'get_object_radius' returns a vector of all 'Creatures' within a radius
vector<Creature*> region = get_object_radius(xpos,ypos,radius);

//I want to go through the retrieved vector and displays all the 'Creature' names
for (vector<Creature*>::iterator i = region.begin(); i != region.end(); ++i) {
    cout<< region[i]->name << endl;
}

Any ideas what I'm doing wrong?

Upvotes: 1

Views: 4841

Answers (3)

Cat Plus Plus
Cat Plus Plus

Reputation: 129954

To get the element iterator is pointing at, you dereference it (like a pointer, but iterators are not necessarily pointers). So your code should look like this:

// auto is C++11 feature
for (auto it = region.begin(); it != region.end(); ++it) {
    Creature *p = *it;
    std::cout << p->name << "\n";
}

In C++11 you also get range for, which hides iterators from your view:

for (Creature *p : region) {
    std::cout << p->name << "\n";
}

Upvotes: 0

Brian Roach
Brian Roach

Reputation: 76918

http://www.cplusplus.com/reference/stl/vector/begin/

You dereference the iterator to get to the underlying object.

cout << (*i)->name << endl;

Upvotes: 4

Charles Salvia
Charles Salvia

Reputation: 53329

Try:

//I want to go through the retrieved vector and displays all the 'Creature' names
for (vector<Creature*>::iterator i = region.begin(); i != region.end(); ++i) {
    cout << (*i)->name << endl;
}

You need to dereference the iterator (using the * operator), which then gives you Creature* pointer.

Upvotes: 1

Related Questions