【发布时间】:2012-01-23 12:29:09
【问题描述】:
如何在 vc++ 中创建通用哈希图?我正在使用 Visual Studio 和 vc++ 作为语言选项。我想将我的实现分成 header(interface) 和 cpp 文件。 标题:
template<class T1,class T2>
class Generic
{
map<T1,T2> m1;
public:
// Standard constructors and destructors
// -------------------------------------
Generic ();
virtual ~Generic ();
// Copy constructor and equal operator
// -----------------------------------
Generic (Generic &);
Generic& operator=(Generic&);
void insert(const T1& key,const T2& value);
T2 lookup(const T1&key);
};
还有我的 cpp 文件:
MyGeneric::Generic()
{
}
//-----------------------------------------------------------------------------
// Generic : destructor
//-----------------------------------------------------------------------------
Generic::~Generic()
{
}
//-----------------------------------------------------------------------------
// Generic : copy constructor
//-----------------------------------------------------------------------------
Generic::Generic(Generic& original)
{
}
//-----------------------------------------------------------------------------
// Generic : equal operator
//-----------------------------------------------------------------------------
Generic& Generic::operator=(Generic& original)
{
return *this;
}
void Generic::insert(const T1& key,const T2& value)
{
}
T2 Generic::lookup(const T1&key)
{
}
我想知道我是否在这里犯了错误。我也对它的用法感到困惑,因为我没有在我的 cpp 文件中定义模板。是这个问题吗?如何删除 hashmap 中对应键的单个值?
【问题讨论】:
-
std::hash_map或std::unordered_map有什么问题? -
@Cody,我们可以通用地使用它们吗,我的意思是我需要一个可以在其中存储任何类型的键值的地图对象。仅基于键及其类型,我需要检索绑定到该键的类型的值..如果我不使用此逻辑,我的程序无疑会变得混乱..
-
@user1061293:两者都是基于模板的通用标准库容器,您实际上是在尝试重新发明轮子。
-
除了所有其他 cmets,您还需要接受一个基本的 c++ 概念:“您不能将模板类的定义与其声明分开并将其放在 .cpp 文件中”。 parashift.com/c++-faq-lite/templates.html#faq-35.12
-
如果您对编写干净的通用 C++ 组件非常感兴趣,请获取 Vandevoorde 和 Josuttis 的C++ 模板:完整指南。您的代码在语法和概念上都有一些缺陷。
标签: c++ templates generics hashmap