Skip to content

Latest commit

 

History

History
136 lines (111 loc) · 3.48 KB

37_exercises.md

File metadata and controls

136 lines (111 loc) · 3.48 KB

< Back

37. std::tuple and structured bindings

Exercise 370

In AtlasMsPacMan.hpp, use a structured binding to "unpack" the MsPacManAnimation parameter and extract out the position into a variable called pos.

What should we do with the other member?

constexpr GridPosition animationFrame(const MsPacManAnimation & animation, Direction direction) {
  switch (direction) {
    case Direction::LEFT:
      return left_animation[animation.position];
    case Direction::RIGHT:
      return right_animation[animation.position];
    case Direction::UP:
      return up_animation[animation.position];
    case Direction::DOWN:
      return down_animation[animation.position];
    case Direction::NONE:
    default:
      return Atlas::pacman_left_narrow;
  }
}
Solution
constexpr GridPosition animationFrame(const MsPacManAnimation & animation, Direction direction) {
  const auto & [pos, _] = animation;
  switch (direction) {
    case Direction::LEFT:
      return left_animation[pos];
    case Direction::RIGHT:
      return right_animation[pos];
    case Direction::UP:
      return up_animation[pos];
    case Direction::DOWN:
      return down_animation[pos];
    case Direction::NONE:
    default:
      return Atlas::pacman_left_narrow;
  }
}

structured binding of a std::array

Solution
  auto [x, y, z] = chars;

structured binding of a struct

Solution
  auto [xx, yy] = q;

structured binding of a std::tuple

Solution
  auto [xx, yy] = q;

structured binding of a std::map

Solution
  std::pair<std::string, int> low_score = std::make_pair("", std::numeric_limits<int>::max());
  for (const auto & [name, score] : map) {
    static_assert(std::is_same_v<decltype((name)), const std::string &>);
    static_assert(std::is_same_v<decltype((score)), const int &>);
    // Find lowest score
    if (score < low_score.second)
      low_score = { name, score };
  }