Hi guys I am making a live flights departure system and in the program I have a vector of Flight objects now I encountered a problem first when I tried this code below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void cleanUpTimeTable(){
for(int i = 0; i < flights.size(); i++){
if(t->tm_hour == flights[i].hour && t->tm_min == flights[i].minute+1){
flights[i].departed = true;
}
}
for(vector<Flight>::iterator it = flights.begin(); it != flights.end();it++){
if(it->departed == true){
flights.erase(it);
}
}
}
the program crashed so I read on the forum that you need to assign it tp flights.erase(it)
it = flights.erase(it),
so how come you have to do this,why can't you just erase the iterator like in my sample code?
second part of the question,I also read that you should increment the iterator outside of the for loop test block
void cleanUpTimeTable(){
for(int i = 0; i < flights.size(); i++){
if(t->tm_hour == flights[i].hour && t->tm_min == flights[i].minute+1){
flights[i].departed = true;
}
}
for(vector<Flight>::iterator it = flights.begin(); it != flights.end();){
if(it->departed == true){
it = flights.erase(it);
}else{
it++;
}
}
}
[code]
how come? why is it when you increment the iterator inside the test block it crashes the program
[code]
void cleanUpTimeTable(){
for(int i = 0; i < flights.size(); i++){
if(t->tm_hour == flights[i].hour && t->tm_min == flights[i].minute+1){
flights[i].departed = true;
}
}
for(vector<Flight>::iterator it = flights.begin(); it != flights.end();it++){
if(it->departed == true){
it = flights.erase(it);
}
}
}
When you erase an element all iterators to that element gets invalided and are no longer safe to use. That is why you need to assign it to another, valid, iterator before you can continue using it. The erase function returns an iterator to the element that comes after the erased element so if you were to increment the iterator (it++) afterwards you would skip the element that comes after the erased element. If the erased element is the last element it means it would equal flights.end() and incrementing that iterator is not allowed and is likely to crash the program.