Practice using algorithms instead of raw for loops.
Use algorithms instead of a raw for loop
in Pellets::isPellet
bool Pellets::isPellet(GridPosition p) const {
for(const GridPosition & position : positions) {
if(position == p)
return true;
}
return false;
}
Hint 1
Look into std::all_of, std::any_of, std::none_of.
Solution
bool Pellets::isPellet(GridPosition p) const {
auto match = [&p](GridPosition pellet) {
return p.x == pellet.x && p.y == pellet.y;
};
return std::any_of(positions.begin(), positions.end(), match);
}
Practice using algorithms instead of raw for loops
in Pellets::eatPelletAtPosition
bool Pellets::eatPelletAtPosition(GridPosition p) {
for(auto it = positions.begin(); it != positions.end(); ++it) {
if(*it == p) {
positions.erase(it);
return true;
}
}
return false;
}
Hint 1
Look into std::find, std::find_if, std::find_if_not.
Solution
bool Pellets::eatPelletAtPosition(GridPosition p) {
auto it = std::find(positions.begin(), positions.end(), p);
if (it == positions.end())
return false;
positions.erase(it);
return true;
}