2010-11-07 95 views
1

我正在學習如何在我的C++大學課程中使用矢量。我遇到了一個讓我無法使用帶矢量迭代器的問題。這是我的源代碼:如何增加矢量迭代器?

template <class T> 
void HuffMan<T>::search_freq(T temp) { 
    //checks for frequency 
    if(objects.empty()){ 
    objects.push_back(temp); 
    return; 
} 

vector<T>::iterator it = objects.begin(); 

while(it != objects.end()) { 
    if(*it == temp) 
    cout<<"added aready\n"; 
    else 
    objects.push_back(temp); 

    //this is where the error occurs 
    //I cannot call 'it++' for some reason 
    it++; 
} 
} 

該代碼總是返回一個運行時錯誤,指出'vector iterator not incrementable'。我試圖將while循環改爲for循環,但我不認爲這與錯誤有關。

信息:我的矢量對象聲明如下:

vector<T> objects; 

誰能幫我針點這個錯誤?

感謝, Y_Y

+0

包含了'霍夫曼'類的方法內while循環? – 2010-11-07 03:38:34

回答

5

你的問題是,你打電話push_back,其中無效迭代後遞增。

這是一個更大問題的症狀。我假設你想測試temp針對vector中的每個元素,如果沒有匹配,則調用push_back,但實際上對於每個不同的元素實際調用push_back

!(所有比賽)!=所有(!比賽)

+0

LOL我可以看到我的錯誤..謝謝... – 2010-11-07 03:44:41

+0

@Y_Y:查看[這個問題](http://stackoverflow.com/questions/4114503/)瞭解更多關於迭代器失效的信息。 – 2010-11-07 12:00:16