@craig.emmerich
Итератор в C++11 может быть реализован с помощью новых функций, таких как begin
и end
, которые возвращают итераторы указывающие на начало и конец контейнера соответственно. Класс итератора должен иметь следующие методы:
Ниже приведен пример реализации итератора для стека:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
template class Stack { private: struct Node { T data; Node* next; Node(const T& data, Node* next = nullptr) : data(data), next(next) {} }; Node* head; size_t size; public: Stack() : head(nullptr), size(0) {} ~Stack() { while (!empty()) pop(); } void push(const T& data) { head = new Node(data, head); size++; } void pop() { if (!empty()) { Node* temp = head; head = head->next; delete temp; size--; } } T top() const { return head->data; } bool empty() const { return head == nullptr; } size_t getSize() const { return size; } // класс итератора class Iterator { private: Node* node; public: Iterator(Node* node) : node(node) {} Iterator& operator++() { node = node->next; return *this; } T& operator*() { return node->data; } bool operator!=(const Iterator& other) const { return node != other.node; } }; Iterator begin() { return Iterator(head); } Iterator end() { return Iterator(nullptr); } }; |
Пример использования:
1 2 3 4 5 6 7 8 |
Stack stack; stack.push(1); stack.push(2); stack.push(3); for (auto it = stack.begin(); it != stack.end(); ++it) { std::cout << *it << ' '; // выводит: 3 2 1 } |