c++ - Increment operator/ iterator implementation -


i trying figure out couple of things here:

  1. how write increment operator node class has pointer next node?
  2. how implement iterators class below?

    #include <iostream> #include <vector> using namespace std;  template <typename t> class node { public:     node(int i=0):val(i) {}     node*& operator++(int i=0) {return next;};      t val;     node *next; };  //================================================ int main() {      node<int> *head, *tmp1, *tmp2;      tmp1 = new node<int>(0);      head = tmp1;      (int i=1; i<10; ++i) {          tmp2 = new node<int>(i);         tmp1->next = tmp2;         tmp1 = tmp2;     }      while (head != null) {          cout << head->val << " '";         head = head->operator++(0);    //how make work ++head;?     } } 

this not example demonstrating operator overloading or iterators.

you don't implement operator++ node class; implement iterator. iterator class should separate class.

and please, don't spoil template making assumptions (since val t, constructor should accept t, not int). also, not ignore int parameter operator++ that: dummy used distinguish pre-increment implementation post-increment implementation.

template <typename t> struct node {     t val;     node *next;      node(const t& t = t()) : val(t) {} };  template <typename t> struct node_iter {     node<t>* current;     node_iter(node<t>* current): current(current) {}      const node_iter& operator++() { current = current->next; return *this; }     node_iter operator++(int) {         node_iter result = *this; ++(*this); return result;     }     t& operator*() { return current->val; } };  int main() {     // make array of nodes, , link them - no point in     // dynamic allocation such simple example.     node<int> nodes[10];     (int = 0; < 10; ++i) {         nodes[i] = node<int>(i);         nodes[i].next = (i == 9) ? nodes + + 1 : 0;     }      // supply pointer first element of array     node_iter<int> test(nodes);     // , iterate:     while (test.current) {         cout << *test++ << " ";     }     // exercise: try linking nodes in reverse order. therefore, create      // 'test' pointer last element of array, rather      // first. however, not need change while loop, because     // of how operator overload works.      // exercise: try writing last while loop loop. not use     // information number of nodes. } 

this still long, long way off providing proper data encapsulation, memory management etc. making proper linked list class not easy. that's why standard library provides one. don't reinvent wheel.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -