0

我已经获得了需要编写代码的模板骨架。我从来没有真正处理过模板。这个模板的奇怪之处在于它要求我们在模板本身中编写一个类——不仅仅是类函数,而是一个全新的类。这是模板的代码(我在一些方法中插入了几行代码只是为了开始,它们对我的问题无关紧要):

包括

template<class K, class V> class HMap
{
 private:
 // insert instance variables
 // insert constants (if any)

 public:
 class MapEntry
 {
    private:
        K key;
        V value;

    public:
    /**
     * Creates a MapEntry.
     * 
     * @param akey the key
     * @param avalue the value
     */
    MapEntry(K akey, V avalue)
    {
        key = akey;
        value = avalue;
    }

    /**
     * Returns the key for this entry.
     * 
     * @return the key for this entry
     */
    K getKey()
    {
        return key;
    }

    /**
     * Returns the value for this entry.
     * 
     * @return the value for this entry
     */
    V getValue()
    {
        return value;
    }

    /**
     * Sets the value for this entry.
     * 
     * @param newValue
     * @return the previous value for this entry
     */
    V setValue(V newValue)
    {
        V oldval;
        oldval = value;
        value = newvalue;
        return oldval;
    }
};

当您创建 HMap 模板类型的对象时,您将如何使用其中的 MapEntry 类?我对模板完全陌生,我有点迷茫,不知道从哪里开始。谢谢你。

4

1 回答 1

0

HMap<Int, Double>::MapEntry引用内部类。但是为什么要暴露内部结构呢?

也许这样做会更容易(我实现了对列表,而不是哈希,因为我很懒)

template <type Key, type Value>
class HashMap {
private:
struct entry { Key key, Value value};
std::list<entry> map;
public:
  HashMap() {};
  void add_element(Key key, Value value)
    {
      entry e = {.key = key, .value = value};
      map.push_back(e);
    };
}
于 2012-12-01T11:50:20.293 回答