1

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*任意のタイプ(明らかに、ハッシュごとに1つのタイプのみ)を使用できるように拡張したいと思います。型を引数とするコンストラクターを定義して考えていたのですが、どうしたらいいのか全くわかりません。それをどのように行うのでしょうか。また、set_attributeがその型を取るように定義されるように、どのように実装するのでしょうか。

コンパイラ:モノ

4

2 に答える 2

2

これを行うには、テンプレートを使用する必要があります。これが例です。

于 2012-07-08T00:03:19.190 に答える
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 のイテレータを使用してアイテムをループしない理由はありますか?

于 2012-07-08T00:06:21.503 に答える