在this question的幫助之後,我使用了對我的類「移動器」的引用來處理矢量中的對象(作爲集合的一部分)。然而,我遇到了問題,我似乎無法確定是什麼原因造成的。看來,一旦我達到了我的向量中的30-35個對象(以僞隨機間隔添加),程序就會停止。沒有崩潰,只是暫停,我必須手動結束任務(CTRL-C不起作用)。引用對象的C++錯誤 - 如何調試?
我的問題似乎在於這些代碼位。我原來:
int main() {
std::vector<Mover> allMovers;
std::vector<Mover>::iterator iter = allMovers.begin();
//This code runs to the end, but the 'do stuff' lines don't actually do anything.
Mover tempMover;
//Other code
while(iter < allMovers.end()) {
tempMover = *iter;
//Do stuff with tempMover
//Add another tempMover at a random interval
allMovers.push_back(CreateNewMover());
iter++;
}
//Other code
}
我的更新對前一個問題鏈接到上面後:
int main() {
std::vector<Mover> allMovers;
std::vector<Mover>::iterator iter = allMovers.begin();
//This code crashes once about 30 or so items exist in the vector, but the 'do stuff' lines do work.
//Other code
while(iter < allMovers.end()) {
Mover& tempMover = *iter;
//Do stuff with tempMover
//Add another tempMover at a random interval
allMovers.push_back(CreateNewMover()); //Crashes here.
iter++;
}
//Other code
}
如何跟蹤下來的任何想法?我有std :: couts遍佈這個地方來標記代碼對我來說。崩潰(雖然發生在不同數量的對象上)始終在push_back()上崩潰,儘管在崩潰之前在同一次運行中多次成功地工作。
編輯
雖然我接受和(認爲)我明白了答案回覆:迭代器,我不明白的是爲什麼代碼DOES工作完全當我不使用的參考目的? (第一個代碼塊)。
另一個編輯 如果有人正在尋找這個具體問題,我的問題的一部分沒有解決:「如何調試?」作爲一名C++新手,我不知道gdb調試器(使用MinGW)。現在我已經知道了它,它在找到這些問題的根源方面非常有幫助。
你是對的,我完全錯過了。 +1 – 2012-03-06 12:51:56
我以前試過索引。但是,當我這樣做時,我遇到了增加循環最大值的問題。當我寫這篇文章時,我可以看到如何避免這種情況,所以我想我會回到那種方法。謝謝! – Gaffi 2012-03-06 13:10:14
@Gaffi:你可以在'while'條件下使用'allMovers.size()'來確保它始終是最新的。 – 2012-03-06 13:29:06