How do I conditionally skip a for loop's post operation in c++ 11?

  • A+
Category:Languages

I have a for loop that iterates through a vector of objects. If an object doesn't meet a condition, I would like to reiterate the same object through the loop until it meets the condition.

int TrainDog(const vector<Dog> &dogs, const Cat big_cat) {      for (auto const dog : dogs) {        dog->Sit();                 // tell the dog to sit        if (!dog->IsBarking())      // if dog isn't barking           dog->Eat(raw_burger);    //   then reward dog        else {                      // else            dog->PlayWith(big_cat);  //   punish dog           ???                      //   and train again ???            big_cat++;               //   with bigger cat        }      }    } 

I would prefer to keep this clean iterator instead of using the traditional index variable syntax.

 


I can think of couple of options.

  1. Use a normal for loop instead of a range-for loop. Increment the iterator only if certain criteria are met.

    int TrainDog(const vector<Dog> &dogs, const Cat big_cat) {     for (auto iter = dogs.begin(); iter != dogs.end(); )    {       auto dog = *iter;       dog->Sit();                 // tell the dog to sit       if (!dog->IsBarking())      // if dog isn't barking       {                    dog->Eat(raw_burger);    //   then reward dog          ++iter;                  // Go on to the next dog       }       else       {           dog->PlayWith(big_cat);  //   punish dog           big_cat++;               //   with bigger cat                                    //   and train again. Don't increment the iterator        }     }    } 
  2. Use a while loop inside the for loop until some criteria are met.

    int TrainDog(const vector<Dog> &dogs, const Cat big_cat) {     for (auto const dog : dogs)    {       while ( true )       {          dog->Sit();                 // tell the dog to sit          if (!dog->IsBarking())      // if dog isn't barking          {             dog->Eat(raw_burger);    //   then reward dog             break;                   //   break out of the while loop          }           dog->PlayWith(big_cat);  //   punish dog          big_cat++;               //   play with bigger cat       }     }    } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: