Insert objects into a hash table (C ++)

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

// 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 am trying to initialize a 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 also tried using" liveStrainTable.insert (...) "in different ways, to no avail.

Would love some help with this. I find it difficult to understand the syntax corresponding to the hash_map SGI, and the SGI link explains almost nothing to me. Thanks.

+3
source share
5 answers

liveStrainTable[ MRCA.c_str() ]= firstStrainPtr;. const char * , MRCA string.

- liveStrainTable :

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

, unordered_map - STL .

+2

hash_map STL. , , hash_map -. -.

Try:

typedef struct {
  size_t operator()( const string& str ) const {
     return __gnu_cxx::__stl_hash_string( str.c_str() );
  }
} strhash;

hash_map< string, Strain *, strhash, eqstr > liveStrainTable;
+1

hash_map const char * , std::string . , , . std::string hashmap MRCA.c_str()

0

. MRCA (), char const *. c_str() char const * ( ) -, .

0

Source: https://habr.com/ru/post/1721428/


All Articles