2

I am learning how to work with vectors in my C++ college class. I have ran into an issue that has been keeping me from using iterators with vectors. This is my source code:

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++;
 }
}

This code always returns a run time error that says 'vector iterator not incrementable'. I have tried to change the while loop into a for loop but I don't think that has to do with anything with the error.

Info: My vector object is declared as follows:

vector<T> objects;

Can anyone help me pin point this error?

Thanks, Y_Y

Y_Y
  • 1,259
  • 5
  • 26
  • 43

1 Answers1

5

Your problem is that you're incrementing after calling push_back, which invalidates the iterator.

This is a symptom of a bigger problem. I assume you want to test temp against every element in the vector and call push_back if there are no matches, but you're actually calling push_back for every element that's different.

!(all match) != all (!match)

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • @Y_Y: Check out [this question](http://stackoverflow.com/questions/4114503/) for more information on iterator invalidation. – Björn Pollex Nov 07 '10 at 12:00