2010-11-07 91 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