fork download
  1. #include <set>
  2. #include <iostream>
  3. #include <memory>
  4.  
  5. class Node;
  6. typedef std::shared_ptr<Node> NodePtr;
  7. class Node {
  8. struct NodeComp {
  9. bool operator()(const NodePtr& p1, const NodePtr& p2) const
  10. {
  11. return p1->getID() < p2->getID();
  12. }
  13. };
  14. int id;
  15. std::set<NodePtr, NodeComp> neighbors;
  16. public:
  17. Node() {}
  18. Node(int newID) : id(newID) {}
  19. int getID() const { return id; }
  20. void addNeighbor(NodePtr newNode)
  21. {
  22. neighbors.insert(newNode);
  23. }
  24. const std::set<NodePtr, NodeComp>& getNeighbors() const
  25. {
  26. return neighbors;
  27. }
  28. bool isNeighbor(int searchID) const
  29. {
  30. return neighbors.count(std::make_shared<Node>(searchID));
  31. }
  32. };
  33.  
  34. int main()
  35. {
  36.  
  37. NodePtr n0 = std::make_shared<Node>(0);
  38. NodePtr n1 = std::make_shared<Node>(1);
  39. NodePtr n2 = std::make_shared<Node>(2);
  40. std::cout << n0->getID() << " adding neighbor " << n1->getID() << '\n';
  41. n0->addNeighbor(n1);
  42. std::cout << n0->getID() << " adding neighbor " << n2->getID() << '\n';
  43. n0->addNeighbor(n2);
  44. std::cout << n1->getID() << " adding neighbor " << n0->getID() << '\n';
  45. n1->addNeighbor(n0);
  46. std::cout << n2->getID() << " adding neighbor " << n1->getID() << '\n';
  47. n2->addNeighbor(n1);
  48. std::cout << n2->getID() << " adding neighbor " << n1->getID() << '\n';
  49. n2->addNeighbor(n1);
  50.  
  51. int id = n0->getID();
  52. auto neighbors = n0->getNeighbors();
  53. std::cout << id << " has " << neighbors.size() << " neighbors. They are: \n";
  54.  
  55. for (auto nb = neighbors.begin(); nb != neighbors.end() ; nb++)
  56. {
  57. auto neighborsList = (*nb)->getNeighbors();
  58. std::cout << " " << (*nb)->getID() << ", which has " << neighborsList.size() << " neighbors: ";
  59. for(auto i = neighborsList.begin(); i!=neighborsList.end(); ++i)
  60. std::cout << (*i)->getID() << ' ';
  61. std::cout << '\n';
  62. }
  63. std::cout << std::boolalpha
  64. << "is 0 a neighbor of 1? " << n1->isNeighbor(0) << '\n'
  65. << "is 1 a neighbor of 0? " << n0->isNeighbor(1) << '\n'
  66. << "is 2 a neighbor of 0? " << n0->isNeighbor(2) << '\n'
  67. << "is 3 a neighbor of 0? " << n0->isNeighbor(3) << '\n';
  68. }
  69.  
Success #stdin #stdout 0s 2972KB
stdin
Standard input is empty
stdout
0 adding neighbor 1
0 adding neighbor 2
1 adding neighbor 0
2 adding neighbor 1
2 adding neighbor 1
0 has 2 neighbors. They are: 
   1, which has 1 neighbors: 0 
   2, which has 1 neighbors: 1 
is 0 a neighbor of 1? true
is 1 a neighbor of 0? true
is 2 a neighbor of 0? true
is 3 a neighbor of 0? false