我正在尝试实现一个哈希表类。我面临的问题是如何正确重载方括号运算符,以便从哈希表中获取键的值与将键设置为值是可区分的。
到目前为止,这是该类的样子:
template <typename K, typename V>
class HashTable {
typedef pair<K, V> KeyVal;
avl_tree <KeyVal> **TABLE;
unsigned TABLESIZE;
public:
HashTable( const unsigned & );
V& operator [] ( const K& ); //Setter
const V& operator [](const K&) const; //Getter
typedef unsigned (*hashtype)(const K&);
static hashtype Hash;
~HashTable();
};
这是括号的每个重载的实现:
template <typename K, typename V>
V& HashTable<K, V>::operator [] ( const K& ret ) {
unsigned index = HashTable<K, V>::Hash(ret) % TABLESIZE;
avl_tree <KeyVal> *ptr = AVL_TREE::find(TABLE[index], KeyVal(ret, 0));
if ( ptr == None ) ptr = (TABLE[index] = AVL_TREE::insert(TABLE[index], KeyVal(ret, 0)));
return ptr->data.second;
}
template <typename K, typename V>
const V& HashTable<K, V>::operator [](const K& ret) const {
avl_tree <KeyVal> *ptr = AVL_TREE::find(TABLE[HashTable<K, V>::Hash(ret) % TABLESIZE], KeyVal(ret, 0));
if (ptr == None) throw "Exception: [KeyError] Key not found exception.";
return ptr->data.second;
}
现在,如果我这样做:
cout << table["hash"] << "\n"; //table declared as type HashTable<std::string, int>
我得到的输出为 0,但我希望它使用重载方括号的 getter 实现;即这应该抛出一个异常。我该怎么做呢?