简体   繁体   中英

How can I increment a vector iterator?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM