2012-02-11 89 views
1

我試圖讓一小段代碼工作。我有一個名爲'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

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

您提領迭代器才能到底層對象。

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

啊,謝謝。我不知道爲什麼我試圖像數組一樣訪問它...... – Matthew 2012-02-11 03:32:22

+0

@Matthew可能是因爲在C中,指針和數組是相同的事情,並且很容易忘記C++迭代器的工作方式不同。 – Crashworks 2012-02-11 03:37:42

+0

如果這是一個被用作數組索引的指針,它將會失敗。 – 2012-02-11 03:42:16

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*指針。

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