访问指针矢量?

时间:2012-02-11 03:26:08

标签: c++ vector

我正在尝试使用一些简单的代码。我有一个名为'get_object_radius'的函数,它在一个区域搜索'Creature'的实例,然后将它们的指针推送到一个向量,然后返回该向量。

然后我想循环遍历它们并从函数外部显示它们的名字。我很确定我正确地将它们添加到向量中,但是我没有正确地遍历指针向量,是吗?

以下是相关的代码段(不起作用):

//'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;
}

任何想法我做错了什么?

3 个答案:

答案 0 :(得分:4)

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

您取消引用迭代器以获取基础对象。

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

答案 1 :(得分:1)

尝试:

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

您需要取消引用迭代器(使用*运算符),然后为您提供Creature*指针。

答案 2 :(得分:0)

要获取迭代器指向的元素,可以取消引用它(就像指针一样,但迭代器不一定是指针)。所以你的代码应该是这样的:

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

在C ++ 11中,您还可以获得范围,从视图中隐藏迭代器:

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