fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. class Book {
  5. private:
  6. std::string name;
  7. public:
  8. Book(){};
  9. Book(std::string name);
  10. ~Book(){};
  11. std::string getName();
  12. friend std::ostream &operator<<(std::ostream &s, Book *b);
  13. };
  14.  
  15. class BookShelfIterator;
  16.  
  17. class BookShelf {
  18. private:
  19. Book **books;
  20. int maxsize;
  21. int last;
  22. public:
  23. BookShelf(int maxsize);
  24. ~BookShelf();
  25. Book *getBookAt(int index);
  26. void appendBook(Book *book);
  27. int getLength();
  28. BookShelfIterator *iterator();
  29. };
  30.  
  31. class BookShelfIterator {
  32. private:
  33. BookShelf *bookShelf;
  34. int index;
  35. public:
  36. BookShelfIterator(BookShelf *bookShelf);
  37. ~BookShelfIterator(){};
  38. bool hasNext();
  39. Book *next();
  40. };
  41. /*-----------------------------------------------*/
  42.  
  43. Book::Book(std::string name) { this->name = name; }
  44. std::string Book::getName() {return this->name; }
  45. std::ostream &operator<<(std::ostream &s, Book *b) {
  46. s << b->name;
  47. return s;
  48. }
  49. /*-----------------------------------------------*/
  50. BookShelf::BookShelf(int maxsize) {
  51. this->books = new Book* [maxsize];
  52. this->maxsize = maxsize;
  53. this->last = 0;
  54. }
  55. BookShelf::~BookShelf() { delete [] (this->books); }
  56. Book *BookShelf::getBookAt(int index) { return this->books[index]; }
  57. void BookShelf::appendBook(Book *book) {
  58. if (last < maxsize) {
  59. this->books[last] = book;
  60. this->last++;
  61. }
  62. }
  63. int BookShelf::getLength() { return this->last; }
  64.  
  65. BookShelfIterator *BookShelf::iterator() { return new BookShelfIterator(this); }
  66.  
  67. /*-----------------------------------------------*/
  68. BookShelfIterator::BookShelfIterator(BookShelf *bookShelf) {
  69. this->bookShelf = bookShelf;
  70. this->index = 0;
  71. }
  72. bool BookShelfIterator::hasNext() {
  73. if (this->index < bookShelf->getLength()) return true;
  74. else return false;
  75. }
  76. Book *BookShelfIterator::next() {
  77. Book *book = bookShelf->getBookAt(index);
  78. index++;
  79. return book;
  80. }
  81.  
  82. template<class T, class U>
  83. void shelf_for_each(T& shelf, U func) {
  84. auto it = shelf->iterator();
  85. while (it->hasNext()) {
  86. func(it->next());
  87. }
  88. delete it;
  89. }
  90.  
  91. int main() {
  92. BookShelf *bookShelf = new BookShelf(4);
  93. bookShelf->appendBook(new Book("A"));
  94. bookShelf->appendBook(new Book("BB"));
  95. bookShelf->appendBook(new Book("CCC"));
  96. bookShelf->appendBook(new Book("DDDD"));
  97. shelf_for_each(bookShelf, [](Book* book){std::cout << book << std::endl;});
  98. delete bookShelf;
  99. return 0;
  100. }
  101.  
Success #stdin #stdout 0s 16056KB
stdin
Standard input is empty
stdout
A
BB
CCC
DDDD