Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // main.cpp
- // iterator
- //
- // Created by Andrei Gavrila on 28/11/2021.
- // Copyright © 2021 Andrei Gavrila. All rights reserved.
- //
- #include <iostream>
- #include <algorithm>
- template <typename T>
- class Node
- {
- public:
- Node *next;
- T value;
- Node(Node<T>* next, T value): next(next), value(value) {}
- };
- template <typename T>
- class List
- {
- private:
- Node<T> *head;
- public:
- struct Iterator
- {
- Iterator(Node<T> *node) : node(node) {}
- T& operator*() const { return node->value; }
- T operator->() { return node->value; }
- Iterator& operator++() { node = node->next; return *this; }
- Iterator operator++(int) { Iterator tmp = *this; ++(*this); return tmp; }
- friend bool operator== (const Iterator& a, const Iterator& b) { return a.node == b.node; };
- friend bool operator!= (const Iterator& a, const Iterator& b) { return a.node != b.node; };
- private:
- Node<T> *node;
- };
- List(): head(nullptr) {}
- void add(T value)
- {
- head = new Node<T>(head, value);
- }
- void print()
- {
- Node<T> *n = head;
- std::cout << "List: [" ;
- while (n)
- {
- std::cout << n->value << (n->next ? ", " : "");
- n = n->next;
- }
- std::cout << "]" << std::endl;
- }
- Iterator begin() {
- return Iterator(head);
- }
- Iterator end()
- {
- return Iterator(nullptr);
- }
- };
- int main(int argc, const char * argv[])
- {
- List<std::string> *list = new List<std::string>();
- list->add("element 1");
- list->add("element 2");
- list->add("element 3");
- list->print();
- for (auto it = list->begin(), end = list->end(); it != end; ++it) {
- const auto s = *it;
- std::cout << s << "\n";
- }
- for (auto s: *list)
- {
- std::cout << s << "\n";
- }
- List<int> *listOfInts = new List<int>();
- listOfInts->add(1);
- listOfInts->add(2);
- listOfInts->add(3);
- int sum = 0;
- for (auto n: *listOfInts)
- {
- sum += n;
- }
- std::cout << "Sum = " << sum << std::endl;
- int sum_quick = 0;
- std::for_each(listOfInts->begin(), listOfInts->end(), [&](int const& n) {sum_quick += n;});
- std::cout << "Sum = " << sum_quick << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement