2009-02-24 58 views
3

有什麼辦法在不同的向量中使用不同類型的迭代器?或者,是否有一個函數將向量中元素的位置作爲整數返回?向量,迭代器和std :: find

std::vector<DWORD>::iterator it;  // Iterator 

// monsterQueue is a <DWORD> vector 

it = std::find(bot.monsterQueue.begin(), bot.monsterQueue.end(), object); 
// Check do we have the object in the queue 

if(it != bot.monsterQueue.end()) // If we do have it 
{ 
    bot.monsterDists.at(it) = mobDist; // monsterDists is <int> vector 
    bot.monsterCoordX.at(it) = PosX; // monsterCoordX is <int> vector 
    bot.monsterCoordY.at(it) = PosY; // monsterCoordY is <int> vector too 
} 

這是一些示例代碼,沒有人有任何指針?

回答

5

嘗試

std::vector<DWORD>::iterator it;  // Iterator 

// monsterQueue is a <DWORD> vector 

it = std::find(bot.monsterQueue.begin(), bot.monsterQueue.end(), object); 
// Check do we have the object in the queue 

if(it != bot.monsterQueue.end()) // If we do have it 
{ 

爲size_t IDX =它 - 機器人.monsterQueue.begin()

bot.monsterDists.at(idx) = mobDist; // monsterDists is <int> vector 
    bot.monsterCoordX.at(idx) = PosX; // monsterCoordX is <int> vector 
    bot.monsterCoordY.at(idx) = PosY; // monsterCoordY is <int> vector too 
} 

也可能它會是一個更好的主意,創建一個結構與4個成員的怪物,monsterDist和coordinateX和coordinateY並存儲向量中的結構對象。

1

您可以使用的std ::矢量的隨機訪問:

DWORD find_this = 0x0; 
int pos = 0; 
for (; i<monsterQueue.size(); ++i) 
{ 
    if (monsterQueue[i]==find_this) 
     break; 
} 

循環後,POS機將是在環路打破,即,其中find_this所在。當然,除非find_this甚至不在矢量中。

6

簡單地計算

it - bot.monsterQueue.begin() 

拿到指標。

+0

+1。我可以建議你也提到,這是有效的,因爲矢量是一個RandomAccessContainer? – 2009-02-24 12:53:44

12
index = std::distance(monsterQueue.begin(), it); 
+0

更好地使用difference_type比int的距離 – 2009-02-24 12:51:34

1

你有沒有想過改變底層類型monsterQueue的到包含或引用/指針monsterDists等物體人