简体   繁体   English

访问指针向量?

[英]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. 我有一个名为“ get_object_radius”的函数,该函数在区域中搜索“ Creature”的实例,然后将其指针推到一个向量,然后返回该向量。

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/ 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. 您需要取消引用迭代器(使用*运算符),然后为您提供Creature*指针。

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: 在C ++ 11中,您还获得了range,它从您的视图中隐藏了迭代器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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