链接列表中的引入运算符

Postincrementation operator in linked list

本文关键字:运算符 列表 链接      更新时间:2023-10-16

我必须编写一个处理此主要代码的程序:(不允许更改它)

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 an exception
  }catch(list<int>::Uninitialized&)
  {
    cout << "Uninitialized map element!" << endl;
  };

这是我的代码:

#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 << "constructorn";
    head = NULL;
    current = NULL;
  }
  ~list ()
  {
    while (head)
      {
        node *t = head->next;
        delete head;
        head = t;
      };
  }
  TYPE read (string ind) const
    {
      cout << "readn";
      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 << "writen";
 node *t = new node;
 t->next = head;
 head = t;
 head->value = value_;
 head->index = ind;
 head->isInit = true;
}  
TYPE operator[] (string ind) const
{
 cout << "readn";
      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

一切都很好,但是只有当我在Main Program中评论启动后操作

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

您可以看到,我有一个结构节点,我将所有变量放在其中,我想在键是" John"的节点中以一个节点增加一个。有什么方法可以为此代码实施操作员 ?我不允许使用std :: map。

您问题的常用方法是将数组下标定义为

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

以这种方式,您不必为operator++打扰一点点:由于iv["John"]返回对int的引用,iv["John"]++将调用内置的int in-increment操作员。

是的,我已经尝试了此解决方案,但是编译器不会区分阅读和写作,而仍使用非const版本。因此,我必须建立有助于区分的代理级别的CREF。我还已经找到了操作员 问题的解决方案。此操作必须来自CREF级别。我创建了

Cref& operator++ (int val)
    {
      s.increment(position,val);
      return *this;
    };

和主体中的增量功能如下:

void increment (string ind, int value_)
{
 cout << "incrementn";
 node *t = head;
 while(t)
 {
    if(t->index == ind && t->isInit == true)    t->value = t->value + 1;
    t = t->next;
 }
}  

完全解决了我的问题。