[英]Accessing Vector of Pointers?
我正在尝试获取一些简单的代码来工作。 我有一个名为“ 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;
}
有什么想法我做错了吗?
尝试:
//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*
指针。
要获取迭代器所指向的元素,可以对其取消引用(就像指针一样,但迭代器不一定是指针)。 因此,您的代码应如下所示:
// auto is C++11 feature
for (auto it = region.begin(); it != region.end(); ++it) {
Creature *p = *it;
std::cout << p->name << "\n";
}
在C ++ 11中,您还获得了range,它从您的视图中隐藏了迭代器:
for (Creature *p : region) {
std::cout << p->name << "\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.