Easy-to-Use Hash Table

Environment: VC6, BC5

The purpose of this article is to show a small hashtable that works with std::strings as key and any data as member.

The hash_map that is implemented as extension of the STL is too complex for my problem and not easy to compile with several compilers (BorlandC, VisualC), so I wrote this little CHashTable class. The class has functions to Add, Remove, and Rename entries and to Get the member data via key. The class is derived from std::list. The Add and Remove functions also push and erase the keys in the parent list class so that you can use the list::iterator functionality.

The class consists of the following member-functions:

CHashTable(long tabsize = 10009, long (*VoidPtr)(const std::string& c, const long prime) = hash_fun1);

Per default, the hash_array has a length of 10009. Of course, you can store more than 10,009 values. You can change the size with argument 1 ( it doesn't have to be a prime number; the constructor adjusts the argument to a prime number).

Argument 2 is the hash function. Per default, it's a the function "hash_fun1" defined in the header file "hash_fun.h".

If the hash_fun calculates equal positions for several keys, the collision is solved via a std::list.

bool AddKey(std::string key, T* member);

Adds a new member with the key "key". If the "key" exists, the function returns false.

bool RenameKey(std::string key, std::string new_key);

Renames the key of the member with the key "key" to "new_key". If the "key" doesn't exist, the function returns false. If the "new_key" exists, the function also returns false.

bool RemoveKey(const std::string& key, bool free_mem = false);

Removes a member with the key "key". If the "key" doesn't exist, the function returns false. If free_mem is true, the memory of the member pointer will be deallocated.

bool RemoveAllKey(bool free_mem = false);

Removes all members (free_mem see "RemoveKey").

T* GetPtr(const std::string& key);

Gets a member with the key "key". If the "key" doesn't exist, the function returns false.

I have added three sample projects that show the usage of the class, and at the end, two examples how to use the class. The first one stores long values in the hash, which are static variables. The second example stores dynamically allocated structs in the table and then reads back one member. After this, all keys are removed and the allocated memory is cleaned up.

/*********************/
/*     Example 1     */
/*     ---------     */
/*  hash with long's */
/*********************/

#include "hash_table.h"

void main()
{
  /* my hash table is of type <long> */
  typedef CHashTable<long> CLongHashT;

  std::string keys[3]    = {"three", "seven", "ten"};
  long        entries[3] = {3, 7, 10};

  /* fill the hash table */
  CLongHashT MyHashTable;
  for(int i = 0; i < 3; i++) MyHashTable.AddKey(keys[i],
                             &entries[i]);

  /* get a member */
  std::string  key     = keys[1];
  long*        pMember = MyHashTable.GetMember(key);
  if(pMember) printf("Entry for key \"%s\" is %d.\n\n",
                      key.c_str(), *pMember);

  /* clean up the hash (do not free memory) */
  MyHashTable.RemoveAllKey(false);
}

/*********************/
/*     Example 2     */
/*     ---------     */
/*  hash with struct */
/*********************/

#include "hash_table.h"

struct SMyStruct
{
  int         fat;
  int         sugar;
  std::string comment;
};

void main()
{
  /* my hash table is of type <SMyStruct> */
  typedef CHashTable<struct SMyStruct> CMyStructHashT;

  /* fill the hash table */
  CMyStructHashT    MyHashTable;
  struct SMyStruct* pStruct = NULL;

  /* first key */
  pStruct = new SMyStruct;
  if(pStruct)
  {
    pStruct->fat     = 0;
    pStruct->sugar   = 622;
    pStruct->comment = "good for tired people";
    MyHashTable.AddKey("cola", pStruct);
  }

  /* second key */
  pStruct = new SMyStruct;
  if(pStruct)
  {
    pStruct->fat     = 15;
    pStruct->sugar   = 0;
    pStruct->comment = "good for young people";
    MyHashTable.AddKey("milk", pStruct);
  }

  /* get a member */
  pStruct = MyHashTable.GetMember("milk");
  if(pStruct) printf("Milk is %s.\n\n", pStruct->comment.c_str());

  /* clean up the hash (and free memory) */
  MyHashTable.RemoveAllKey(true);
}

Downloads

Download demo project - 22 Kb
Download source - 5 Kb


Comments

  • qzgbqrz

    Posted by gronfonge on 06/11/2013 02:25am

    Of the the fashion components out there with the industry nowadays, the actual glasses are those who become mandatory for a trend significant other. [url=http://www.okaleymallsja.com/]http://www.okaleymallsja.com/[/url],As opposed to the actual the past when people utilized to declare you will be a way lover, your current wallet possesses gotta end up being huge? [url=http://www.katespadeya.com/]ケイトスペード バッグ 新作[/url],today the method accessories including the sun shades can be bought in low-priced costs.[url=http://www.katespadenyuja.com/]ケイトスペード バッグ[/url], Before, everyone was determined by typically the look-alike sunglasses, since they weren't manage to obtain the designer top quality shades. There was perhaps reviews the fact that brand name custom made sun shades had been just for the celebs but not to your common human being.[url=http://www.coachoffsite.com/]http://www.coachoffsite.com/[/url], Stuff include changed quite a lot throughout the previous 10 years. A result of the high level of competition among the many developer sun glasses producers, all these brand name types are offered by very reasonably priced prices. [url=http://www.katespadenyuja.com/]ケイトスペード 財布 2013[/url],An additional for that affordable costs of the developer sun shades will be the massive regarding the same among the list of vogue enthusiasts. This holiday season, the trend enthusiasts have an overabundance of versus the low-priced prices to acquire pleased. The popular developer sunglass companies get presented several fresh styles having very economical costs. [url=http://www.coachoffsite.com/]コーチ 財布[/url],Simply keep on looking at within the content for more information concerning the brand new custom made glasses. Given its name the actual president of the Armani sunglasses, the particular Giorgio Armani sun glasses are the latest fascination. [url=http://www.okaleymallsja.com/]オークリー サングラス[/url],In contrast to the standard distinct sun shades by Armani, the actual Giorgio Armani Glasses are extremely properly price. All these Giorgio Armani shades are usually examples for the undeniable fact that ashion arguments are definitely not just for the actual superstars.[url=http://www.katespadeya.com/]ケイトスペード バッグ 新作[/url],Infact each style fan on the market ought to personal one of the Giorgio Armani shades due to the quite deluxe appearance.

    Reply
  • dzuukhvcp

    Posted by chuscumsMup on 06/10/2013 04:27am

    Practice with the obligation PGA Expert instructor. [url=http://www.coachfactorysite.com/]コーチ アウトレット[/url],You can find a couple of major points to consider when choosing the golf instructor: 1) their very own power to train and also transform your game; and 2) all their number of buddies with higher education mentors. Initial, you might be training to enhance what you want. The actual the sport of golf master can be Tiger Woods, however he can not teach you just how toplay a great deal better, this individual isn't very rugged and reliable. 2nd, specialist instruction additionally achieves your next target, receiving observed by higher education motor coach buses. [url=http://www.coachfactorysite.com/]コーチ 財布[/url],The trainer you select ought to be famous and respected by simply school motor coach buses, and also have numerous relationships on big and more compact educational institutions. Employment interview and get golf professionals the number of motor coach buses that they knowand exactly how nicely they learn these people. Talk with past as well as current students of often the would-be positives of these educating power. Help to make proven to the ideal folks your objective to play the game of golf in higher education. The most crucial reduce weight explain to on your motives are generally your golf trainer and also graduating high school golf instructor, should you have just one. [url=http://www.coachfactorysite.com/]コーチ バッグ 2013[/url],These are the basic a family having possible scarves for you to and relationships with university motor coach buses. Won't people do you know compliment will certainly take one of the most fat. Have fun with inside junior playing golf tournament. University golfing, just like every other sports activity, will involve stress involving levels of competition.[url=http://www.coachfactorysite.com/]コーチ バッグ メンズ[/url], Motor coach buses understand that if a would-be player has become associated with level of competition and also fared nicely, they've been exposed to event tension. An individual succeed tournament, while which absolutely more suitable you just have to participate in and also performyour best. Great results within difficult the weather is one of many variables thatget you actually observed. [url=http://www.coachfactorysite.com/]コーチ バッグ[/url],Nearly every spot throughout the country includes a younger golf association or even jr golfing vacation that conducts competitions. [url=http://www.coachfactorysite.com/]www.coachfactorysite.com[/url] コーチ アウトレット,Discover these competitions and enjoy. Higher education instructors will likely be observing your own personal results and also recollecting labels.

    Reply
  • Nice one there

    Posted by Slalaleasyday on 03/14/2013 04:37pm

    Nice Post. ---------- I love http://youtube.com

    Reply
  • http://www.moncleroutletstop.com l8I7u1

    Posted by crafeWermof on 11/06/2012 04:50pm

    The top clothes will Moncler Vests be the Moncler clothing, which suits absolutely everyone, which has Moncler Jackets a label of http://www.moncleroutletstop.com/ extended history which are the ideal Moncler Outlet mixture of style and sports. It was initial introduced within the year of 1952, http://www.moncleroutletstop.com/ near a town named Grenoble in France. The founder in the brand was a Frenchman named as Rene Ramillon who became relatively much renowned by these Moncler Clothing, and his name came from an Moncler Jackets Online abbreviation on the mountain village, that is named because the Monastier de Clermont that is incredibly close to Grenoble

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • You probably have several goals for your patient portal of choice. Is "community" one of them? With a bevy of vendors offering portal solutions, it can be challenging for a hospital to know where to start. Fortunately, YourCareCommunity helps ease the decision-making process. Read this white paper to learn more. "3 Ways Clinicians can Leverage a Patient Portal to Craft a Healthcare Community" is a published document owned by www.medhost.com

  • The impact of a data loss event can be significant. Real-time data is essential to remaining competitive. Many companies can no longer afford to rely on a truck arriving each day to take backup tapes offsite. For most companies, a cloud backup and recovery solution will eliminate, or significantly reduce, IT resources related to the mundane task of backup and allow your resources to be redeployed to more strategic projects. The cloud - can now be comfortable for you – with 100% recovery from anywhere all …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds