2012-07-07 113 views
1

我有以下代码实现简单散列/字典在C++以一个类型作为参数的函数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]; 
     } 
    } 
} 

目前,它可以作为一个键/值的唯一类型是const char*,但我想扩展它,使它c采取任何类型(显然每个散列只有一种类型)。我正在考虑通过定义一个以类型作为参数的构造函数来实现这一点,但在这种情况下我完全不知道如何去做。我该怎么做,我将如何实现它,所以set_attribute被定义为采取这种类型?

编译:单

+8

你有没有听说过模板?他们非常有用。 – chris 2012-07-07 23:59:25

+1

'std :: map'或'std :: unordered_map'如何? – bitmask 2012-07-08 01:16:42

+0

这与Mono有什么关系? – skolima 2012-07-08 12:18:40

回答

2

您需要使用templates做到这一点。 Here就是一个例子。

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 

请注意,我已删除using namespace std;,因为它完全消除其命名空间的全部要点,尤其是在头文件。

编辑:另外,是否有任何理由不使用std :: vector的迭代器来遍历它的项目?

相关问题