0

i am trying to build a dictionary in cpp that takes 2 template argumemts (), and i have a "get" function that should return the value only.

this is the class header:

#include <iostream>
#include <vector>
using namespace std;

template <class K, class V>
class Dict {
protected:
    vector<K> keys;
    vector<V> values;
    K Key;
    V Value;
public:
    Dict();
    void set(K Key, V Value);
    V get(string key);
};

this is the class cpp:

#include "Dict.h"
template <class K, class V>
Dict<K,V>::Dict() {};

template <typename K, typename  V>
V Dict<K,V>::get(K key) {
    V lol;
    bool found = false;
    for(int i = 0; i < this->keys.size(); i++){
        if(this->keys[i] == key){
            return *this->values[i];

        }
    }
    cout << "This Key does not exists";
    return lol;
}
template <typename K, typename  V>
void Dict<K,V>::set(K Key, V Value) {
    keys.push_back(Key);
    values.push_back(Value);
}

template class Dict<string, int>;

this is the main:

#include "Dict.h"
int main() {
    Dict<string, int> d;
    d.set("yoav", 34);
    d.set("hey", 8);
    int num = d.get("hey");

    cout << num;
    return 0;
}

and the compiler throws this:

error: prototype for ‘V Dict<K, V>::get(K)’ does not match any in class ‘Dict<K, V>’
 V Dict<K,V>::get(K key) {
   ^
  • Possible duplicate of [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Yksisarvinen Jul 23 '18 at 07:52
  • 2
    You declaration for that member function has `string` for the parameter type. – Mat Jul 23 '18 at 07:52
  • Note that `std::map` already exist. – Jarod42 Jul 23 '18 at 08:29

1 Answers1

0

Besides the fact, that you should put the template-implementation not in the cpp-file, but into the header, there is an other error.

return *this->values[i];

should be either

return this->values[i];

or

return (*this).values[i];

And the working(=compiling) code

#include <iostream>
#include <vector>
using namespace std;

template <class K, class V>
class Dict {
protected:
    vector<K> keys;
    vector<V> values;
    K Key;
    V Value;
public:
    Dict() {

    }
    void set(K Key, V Value) {
        keys.push_back(Key);
        values.push_back(Value);
    }

    V get(string key) {
        V lol;
        bool found = false;
        for(int i = 0; i < this->keys.size(); i++){
            if(this->keys[i] == key){
                return this->values[i];

            }
        }
        cout << "This Key does not exists";
        return lol;
    }
};

int main() {
    Dict<string, int> d;
    d.set("yoav", 34);
    d.set("hey", 8);
    int num = d.get("hey");

    cout << num;
    return 0;
}
Domso
  • 970
  • 1
  • 10
  • 22
  • 1
    And "biggest" problem is that `Key` might be different than `std::string` (so `get` signature should be fixed). – Jarod42 Jul 23 '18 at 09:06