Skip to content

Latest commit

 

History

History
94 lines (68 loc) · 1.82 KB

23_exercises.md

File metadata and controls

94 lines (68 loc) · 1.82 KB

< Back

23. Iterators and Algorithms

Exercise 230

Use algorithms to implement Pellets::isPellet

Practice using algorithms instead of raw for loops.

Exercise

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);
}

Exercise 231

Use algorithms to implement Pellets::eatPelletAtPosition

Practice using algorithms instead of raw for loops in Pellets::eatPelletAtPosition

Exercise

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;
}