I am using C++, I have a vector of paired variables, for which the first element is a vector and the second element is an integer. My problem is that I am trying to remove certain elements from this vector, and can’t seem to get it to work!
The code is shown below, and everything is working as I’d expect up to the line:
vec1.erase(i);
as I can cout some other relevant variables from the vector to the screen, and they are correct.
compareVecs is just an element of this class that compares some variables.
void myCode::PairRemoval(vector<myTypeDef> &vec1, const vector<myTypeDef> &vec2, double conditionMax) {
bool condition=false;
for (unsigned int i=0; i<vec1.size(); i++){
for (unsigned int j=0; j<vec2.size(); j++){
if (vec1[i].first.compareVecs(vec2[j].first) <= conditionMax) {
condition = true;
break;
}
}
if (condition) {
vec1.erase(i);
cout<<"removed"<<endl;
}
}
}
I hope to remove the pair from this vector, if the condition is met.
Thanks in advance for any help!
You shouldn’t iterate a vector AND erase elements inside the loop. When you erase elements, the vector size changes and the indexes also change. A recommended way would be to store the elements you have to remove in another structure (like a vector) and then loop to remove them.