我必须编写一个处理该主要代码的程序:(不允许更改)
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 << "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
一切都很好,但是只有当我在主程序中注释掉后增量操作时,
int ia = iv["john"]++;
如您所见,我有一个struct节点,在其中放置了所有变量,并且我想在键为“john”的节点中将值增加1。有什么办法可以为此代码实现operator ++吗?
我不允许使用std::map。
最佳答案
解决问题的常用方法是将数组下标运算符定义为
const TYPE& operator[](string ind) const;
TYPE& operator[](string ind);
这样,您就不必为
operator++
操心了:由于iv["John"]
返回对int
的引用,因此iv["John"]++
将调用内置的int
后递增操作符。关于c++ - 链表中的后增量运算符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21596402/