将对象插入哈希表(C ++) [英] Inserting objects into hash table (C++)

查看:140
本文介绍了将对象插入哈希表(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次创建哈希表。我试图将字符串(键)与类Strain的对象(数据)的指针相关联。

This is my first time making a hash table. I'm trying to associate strings (the keys) with pointers to objects (the data) of class Strain.

// Simulation.h
#include <ext/hash_map>
using namespace __gnu_cxx;

struct eqstr
{
 bool operator()(const char * s1, const char * s2) const
  {
   return strcmp(s1, s2) == 0;
  }
};

...
hash_map< const char *, Strain *, hash< const char * >, struct eqstr > liveStrainTable;

在Simulation.cpp文件中,我尝试初始化表:

In the Simulation.cpp file, I attempt to initialize the table:

string MRCA;
for ( int b = 0; b < SEQ_LENGTH; b++ ) {
  int randBase = rgen.uniform(0,NUM_BASES); 
  MRCA.push_back( BASES[ randBase ] );
}
Strain * firstStrainPtr;
firstStrainPtr = new Strain( idCtr, MRCA, NUM_STEPS );
liveStrainTable[ MRCA ]= firstStrainPtr;



我收到一条错误消息,在 *)this) - > Simulation :: liveStrainTable [MRCA]'。我也试过以不同的方式使用liveStrainTable.insert(...),没有效果。

I get an error message that reads "no match for ‘operator[]’ in ‘((Simulation*)this)->Simulation::liveStrainTable[MRCA]’." I've also tried using "liveStrainTable.insert(...)" in different ways, to no avail.

真的会喜欢一些帮助。我很难理解适用于SGI hash_map的语法,以及 SGI参考几乎不能澄清任何东西给我。感谢。

Would really love some help on this. I'm having a difficult time understanding the syntax appropriate for SGI hash_map, and the SGI reference barely clarifies anything for me. Thanks.

推荐答案

尝试 liveStrainTable [MRCA.c_str()] = firstStrainPtr; 。它期望 const char * 作为键值的类型,但 MRCA 有类型 string

Try liveStrainTable[ MRCA.c_str() ]= firstStrainPtr;. It expects const char * as type of key value, but MRCA has type string.

另一种方法是将 liveStrainTable 更改为:

Another way is to change liveStrainTable to:

hash_map< string, Strain *, hash<string>, eqstr > liveStrainTable;

这篇关于将对象插入哈希表(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆