1

I have the following code which implements a simple Hash/Dict in C++

Hash.h

using namespace std;

#include <string>
#include <vector>

class Hash
{
  private:
    vector<const char*> key_vector;
    vector<const char*> value_vector;
  public:
    void set_attribute(const char*, const char*);
    string get_attribute(const char*);
};

Hash.cpp

using namespace std;

#include "Hash.h"

void Hash::set_attribute(const char* key, const char* value)
{
    key_vector.push_back(key);
    value_vector.push_back(value);
}

string Hash::get_attribute(const char* key)
{
    for (int i = 0; i < key_vector.size(); i++)
    {
        if (key_vector[i] == key)
        {
            return value_vector[i];
        }
    }
}

At the moment, the only type it can take as a key/value is a const char*, but I want to extend it so that it can take any type (obviously only one type per hash). I was thinking about doing that by defining a constructor which takes a type as an argument, but I don't know at all how to do that in this situation. How would I do that, and how would I implement it so set_attribute is defined to take that type?

Compiler: Mono

Bobby Tables
  • 1,154
  • 4
  • 15
  • 25

2 Answers2

2

You need to use templates to do this. Here is an example.

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
2
#ifndef HASH_INCLUDED_H
#define HASH_INCLUDED_H

#include <string>
#include <vector>

template <typename T>
class Hash
{
  private:
    std::vector<const T*> key_vector;
    std::vector<const T*> value_vector;
  public:
    void set_attribute(const T*, const T*)
    {
        /* you need to add definition in your header file for templates */
    }
    T* get_attribute(const T*)
    {
        /* you need to add definition in your header file for templates */
    }
};

#endif

Please note that I have removed using namespace std; as it completely removes the entire point of having namespaces, especially in header files.

Edit: Also, is there any reason why you are not using std::vector's iterator to loop through its items ?

ApplePie
  • 8,814
  • 5
  • 39
  • 60