Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting objects into hash table (C++)

Tags:

c++

hashmap

sgi

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;

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;

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.

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.

like image 865
Sarah Avatar asked Nov 26 '25 01:11

Sarah


2 Answers

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

Another way is to change liveStrainTable to:

hash_map< string, Strain *, hash<string>, eqstr > liveStrainTable;
like image 127
Kirill V. Lyadvinsky Avatar answered Nov 27 '25 13:11

Kirill V. Lyadvinsky


Others answered your direct question, but may I suggest using unordered_map instead - it's coming with the next version of the STL and is supported by all major compilers.

like image 23
Nikolai Fetissov Avatar answered Nov 27 '25 13:11

Nikolai Fetissov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!