fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3. #include <tuple>
  4. #include <map>
  5.  
  6. struct Position { int x, y; };
  7. bool operator<(Position const &a, Position const &b)
  8. {
  9. return std::tie(a.x, a.y) < std::tie(b.x, b.y);
  10. }
  11. std::ostream &operator<<(std::ostream &os, Position const &p)
  12. {
  13. return os << '(' << p.x << ", " << p.y << ')';
  14. }
  15.  
  16. struct Board
  17. {
  18. class Piece
  19. {
  20. Position p;
  21. friend struct ::Board;
  22. public:
  23. Position const &pos = p;
  24. Piece(Position const &p)
  25. : p(p)
  26. {
  27. }
  28. };
  29.  
  30. void swap(Position const &source, Position const &target)
  31. {
  32. std::cout << "Swapping " << source << " to " << target << std::endl;
  33. pieces[target].swap(pieces[source]);
  34. pieces[target]->p = target;
  35. pieces[source]->p = source;
  36. std::cout << "Swapped " << source << " to " << target << std::endl;
  37. }
  38.  
  39. void add(Position const &p)
  40. {
  41. pieces[p] = std::unique_ptr<Piece>(new Piece(p));
  42. }
  43. Piece *at(Position const &p)
  44. {
  45. return pieces[p].get();
  46. }
  47.  
  48. private:
  49. std::map<Position, std::unique_ptr<Piece>> pieces;
  50. };
  51.  
  52. int main()
  53. {
  54. Board b;
  55. b.add({1, 1});
  56. b.add({1, 2});
  57. b.add({2, 1});
  58. b.add({2, 2});
  59.  
  60. std::cout << "First swap:" << std::endl;
  61. b.swap({1, 1}, {1, 2});
  62. std::cout << std::endl
  63. << "Second swap:" << std::endl;
  64. b.swap(b.at({2, 1})->pos, {2, 2});
  65. }
  66.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
First swap:
Swapping (1, 1) to (1, 2)
Swapped  (1, 1) to (1, 2)

Second swap:
Swapping (2, 1) to (2, 2)
Swapped  (2, 2) to (2, 2)