我有一个循环遍历对象向量。如果一个对象不满足条件,我想通过循环重复同一个对象,直到它满足条件。
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
}
}
}
我更愿意保留这个干净的迭代器,而不是使用传统的索引变量语法。
我可以想到几个选项。
使用普通for
循环而不是范围for
循环。仅在满足某些条件时才增加迭代器。
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
}
}
}
在while
循环内使用for
循环,直到满足某些条件。
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
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句