【问题标题】:Take a type as a parameter to a function C++将类型作为函数 C++ 的参数
【发布时间】:2012-07-07 22:36:22
【问题描述】:

我有以下代码在 C++ 中实现了一个简单的 Hash/Dict

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*,但我想扩展它以便它可以采用任何类型(显然每个哈希只有一种类型)。我正在考虑通过定义一个将类型作为参数的构造函数来做到这一点,但我根本不知道在这种情况下如何做到这一点。我将如何做到这一点,我将如何实现它以便将 set_attribute 定义为采用该类型?

编译器:单声道

【问题讨论】:

  • 你听说过模板吗?它们非常有用。
  • std::mapstd::unordered_map 怎么样?
  • @bitmask,我只是在学习 C++,我实现它只是为了帮助我学习东西 :-)

标签: c++ types dictionary mono arguments


【解决方案1】:
#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 的迭代器来循环其项目?

【讨论】:

    【解决方案2】:

    您需要使用templates 来执行此操作。 Here 就是一个例子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      相关资源
      最近更新 更多