如何增加向量迭代器?

Y_Y*_*Y_Y 1 c++ vector

我正在学习如何在我的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++;
 }
}
Run Code Online (Sandbox Code Playgroud)

此代码始终返回运行时错误,该错误表示"矢量迭代器不可递增".我试图将while循环更改为for循环,但我不认为这与错误的任何事情有关.

信息:我的矢量对象声明如下:

vector<T> objects;
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我指出这个错误吗?

谢谢,Y_Y

Ben*_*igt 5

你的问题是你在调用后递增push_back,这会使迭代器失效.

这是一个更大问题的症状.我假设你想测试并调用temp中的每个元素,如果没有匹配,但你实际上是在调用每个不同的元素.vectorpush_backpush_back

!(全部匹配)!=全部(!匹配)