C++ 将类接口转换为类模板

C++ 将类接口转换为类模板,c++,C++,我正在看一些没有备忘的旧试卷。我只是想确保我正确理解这一点 提供模板类的接口 字典 这就是提供的场景 class Dictionary { public: Dictionary(); void Add(int key, const string &value); string Find (int key) const; private: vector<int> Keys; vec

我正在看一些没有备忘的旧试卷。我只是想确保我正确理解这一点

提供模板类的接口

字典
这就是提供的场景

class Dictionary {
    public:
        Dictionary();
        void Add(int key, const string &value);
        string Find (int key) const;
    private:
        vector<int> Keys;
        vector <string> Values;
};
类字典{
公众:
字典();
void Add(int键、常量字符串和值);
字符串查找(int键)常量;
私人:
向量键;
向量值;
};
这就是我写下的解决方案

class Dictionary {
    public:
        Dictionary();
        void Add(TKey key, const TValue &value);
        TValue Find (TKey key) const;
    private:
        vector <Dictionary> Keys;
        vector <Dictionary> Values;
};
类字典{
公众:
字典();
无效添加(TKey键、const TValue和value);
TValue Find(TKey)const;
私人:
向量键;
向量值;
};
对我来说,这似乎是正确的。我还没有为此编译驱动程序,因为我只是想确保在给定模板类的情况下正确理解它

我想最后两行向量是我想要确保我写的正确的地方


感谢您抽出时间。

您只需按照说明操作即可:

template<typename Tkey, typename TValue> // <<<<<<<<
class Dictionary {
public:
    Dictionary();
    void Add(TKey key, const TValue &value);
    TValue Find (TKey key) const;
private:
    vector <TKey> Keys; // <<<<<<<<
    vector <TValue> Values; // <<<<<<<
};

template/此转换不完整,并且稍有错误

要使其完整,请确保该类实际上是一个类模板,即

template <typename TKey, typename TValue>
class Dictionary {
    ...
};
模板
类词典{
...
};

纠正方法是使两个向量采用键和值。目前,两个向量都设置为存储
字典
元素,这不是您所需要的:第一个向量应该包含
TKey
元素,而第二个向量应该包含
TValue
s。只要开始实现
Dictionary::Find
方法,您就会发现这个缺点。

Dictionary
的成员向量不能是
Dictionary
s
template<typename Tkey, typename TValue> // <<<<<<<<
class Dictionary {
public:
    Dictionary();
    void Add(TKey key, const TValue &value);
    TValue Find (TKey key) const;
private:
    vector <std::pair<TKey,TValue>> dict; // <<<<<<<
};
template <typename TKey, typename TValue>
class Dictionary {
    ...
};