简体   繁体   中英

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?

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

You dereference the iterator to get to the underlying object.

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

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.

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM