c++ - Postincrementation operator in linked list -


i had write program handle main code:(not allowed change it)

list<int> iv;    iv["john"] = 23;    int ia = iv["john"]++;   int ib = iv["john"];    cout << ia << " " << ib << endl; // prints 23 24   try{   cout << iv["jack"] << endl;   // should throw exception   }catch(list<int>::uninitialized&)   {     cout << "uninitialized map element!" << endl;   }; 

here code:

#ifndef exam_h #define exam_h #include <iostream> #include <string>  using namespace std;  template <class type> class list { private: struct node {   type value;   string index;   bool isinit;   node *next; }; node *head; node *current; public:   class cref   {     friend class list;     list& s;     string position;     cref (list& ss, string pos): s(ss), position(pos) {};   public:     operator type() const     {       return s.read(position);     }     cref& operator = (type val)     {       s.write(position,val);       return *this;     };     cref& operator = (const cref& ref)     {       return operator= ((type)ref);     };   };   class uninitialized{};   list ()   {     cout << "constructor\n";     head = null;     current = null;   }    ~list ()   {     while (head)       {         node *t = head->next;         delete head;         head = t;       };   }    type read (string ind) const     {       cout << "read\n";       node *t = head;       while(t)       {         if(t->index == ind && t->isinit == true)    return t->value;         else t = t->next;       }       throw uninitialized();     }    void write (string ind, type value_) {  cout << "write\n";  node *t = new node;  t->next = head;  head = t;  head->value = value_;  head->index = ind;  head->isinit = true; }    type operator[] (string ind) const {  cout << "read\n";       node *t = head;       while(t)       {         if(t->index == ind && t->isinit == true)    return t->value;         else t = t->next;       }       throw uninitialized(); }  cref operator[] (string ind) {   return cref(*this, ind); }  }; #endif 

everything works great, when comment out postincrementation operation in main program

int ia = iv["john"]++; 

as can see have struct node put variables , want increment value 1 in node key "john". there way implement operator++ code ? not allowed use std::map.

the usual approach problem defining array subscript operators

const type& operator[](string ind) const; type& operator[](string ind); 

in way, not have bother single bit operator++: since iv["john"] returns reference int, iv["john"]++ call int post-increment operator built-in.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -