How to use the Hashtable collection in Visual C++

For a Microsoft Visual C# .NET version of this article, see
309357 .
For a Microsoft Visual Basic .NET version of this article, see
307933 .

IN THIS TASK

Summary

This step-by-step article describes how to use the Hashtable collection. By using hashing to retrieve the data, you do not have to use the costly searching mechanism. Hashing uses the value of the key itself to locate the data.

The Base Class Libraries offer a Hashtable class that is defined in the System.Collections namespace so that you do not have to code your own hash tables.

back to the top

Requirements

This article assumes that you are familiar with the following topics:
  • Microsoft Visual Studio .NET or Microsoft Visual Studio 2005
  • Microsoft .NET Framework fundamentals
  • Object-oriented programming concepts
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Visual Studio .NET 2003 or Microsoft Visual Studio 2005
  • The Microsoft .NET Framework 1.1
back to the top

Steps to build the sample

A Hashtable collection stores a key-and-value pair (key, value). The Hashtable collection uses the key to hash and obtain the storage location. The key is immutable and cannot have duplicate entries in the Hashtable collection. This sample uses several instances of a simple Person class to store records in a Hashtable collection. The last name is used as the key.
  1. Start Visual Studio .NET 2003 or Microsoft Visual Studio 2005.
  2. On the File menu, point to
    New, and then click Project.
  3. Under
    Project Types, click Visual C++ Projects.

    Note In Microsoft Visual Studio 2005, click Visual C++ under Project Types.
  4. Under Templates, click Windows Forms Application (.NET).

    Note In Microsoft Visual Studio 2005, click Windows Forms Application under Templates.
  5. In the Name box, type
    815673, and then click OK.

    By default, Form1 is added to the project.
  6. On the Project menu, click Add Class.
  7. In the Add Class dialog box, click
    Generic C++ Class under Templates, and then click Open.

    Note In Microsoft Visual Studio 2005, click C++ Class under Templates.
  8. In the Generic C++ Class Wizard, type
    Person in the Class name box, and then click Finish.
  9. Open the Person.cpp file, and then delete the code for the constructor and the code for the destructor.
  10. Open the Person.h file, and then replace the existing code with the following code.
    #pragma once
    using namespace System;

    public __gc class Person
    {
    public:
    String *Fname, *Lname;
    public:
    Person(String *FirstName, String *LastName)
    {
    Fname = FirstName;
    Lname = LastName;
    }

    String* ToString()
    {
    return String::Concat(Fname, S" ",Lname);
    }
    };
    The Person class has one constructor that takes the FirstName parameter and the LastName parameter. It assigns these parameters to the local variables. The ToString function overrides the ToString function from the Object class to return the Fname value and the Lname value concatenated together.

    Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile this code sample. To do this, follow these steps:

    1. Click Project, and then click ProjectName Properties.

      Note ProjectName represents the name of the project.
    2. Expand Configuration Properties, and then click General.

    3. Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting on the right pane, click Apply, and then click OK.

    For more information about the common language runtime support compiler options, visit the following Microsoft Web site:
    /clr (Common Language Runtime Compilation)
    http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx
    These steps apply to the whole article.le.
  11. Switch to Form1.h[design], and then press F7 to open the Form.h file. Paste the following code in the Form1.h file.
    #include "Person.h"
  12. Declare a class variable of type Hashtable, and then declare three class variables of type Person class.
  13. Add the following code to the Form1 class:
    public:
    Hashtable *MyTable;
    //For simplicity, create three Person objects to add to the Hashtable collection.
    Person *Person1,*Person2,*Person3;
  14. To create an instance of the Hashtable object, add the following code in Form1 class constructor after the call for the InitilizeComponent method.
    MyTable = new Hashtable();
  15. In the following steps, use the Add method of the Hashtable object to add three Person objects to the Hashtable object in a try-catch block. The try-catch block catches the exception and displays a message if duplicate keys exist.
    1. Add a Button control to the Form1 form, and then change the Text property of the Button control to
      Add Items.
    2. Double-click the button1 control, and then paste the following code in the
      button1_Click event.
      Person1 = new Person(S"David", S"Burris");
      Person2 = new Person(S"Johnny", S"Carrol");
      Person3 = new Person(S"Ji", S"Jihuang");

      //The Add method takes the key as the first parameter and the value as the second parameter.
      try
      {
      MyTable->Add(Person1->Lname, Person1);
      MyTable->Add(Person2->Lname, Person2);
      MyTable->Add(Person3->Lname, Person3);
      }

      catch (ArgumentException *ae)
      {
      MessageBox::Show(S"Duplicate Key");
      MessageBox::Show(ae->Message);
      }
  16. The Hashtable object provides an indexer. In the following steps, index by using the key to access the value that is stored at the hashed location.
    1. Add a Button control to the Form1 form, and then change the Text property of the Button control to Get Items.
    2. Double-click the button2 control, and then paste the following code in the button2_Click event.
      //Use the indexer of the Hashtable class to retrieve your objects. The indexer takes 
      //the key as a parameter and accesses it by using the hashed location.
      try
      {
      MessageBox::Show(MyTable->get_Item(Person1->Lname)->ToString());
      MessageBox::Show(MyTable->get_Item(Person2->Lname)->ToString());
      MessageBox::Show(MyTable->get_Item(Person3->Lname)->ToString());
      }
      catch (NullReferenceException *ex)
      {
      MessageBox::Show(S"Key not in Hashtable");
      MessageBox::Show(ex->Message);
      }
  17. In the following steps, use the Remove method to remove a single item from the Hashtable collection.
    1. Add a Button control to the Form1 form, and then change the Text property of the Button control to Remove Item.
    2. Double-click the button3 control, and then paste the following code in the button3_Click event.
      if (MyTable->Count == 0) 
      {
      MessageBox::Show(S"There are no items in HashTable");
      }
      else
      {
      MessageBox::Show(String::Concat(S"The count before removing an Item is ",MyTable->Count.ToString()));
      MessageBox::Show(S"Removing value stored at key value (Burris)");
      //Remove the object that is stored at the key value Person1.Lname.
      MyTable->Remove(Person1->Lname);
      }
  18. In the following steps, enumerate the items that are stored in the Hashtable collection.
    1. Add a Button control to the Form1 form, and then change the Text property of the Button control to
      Enumerate.
    2. Double-click the button4 control, and then paste the following code in the button4_Click event.
      IDictionaryEnumerator *Enumerator;

      if (MyTable->Count == 0)
      {
      MessageBox::Show(S"The hashtable is empty");
      }
      else
      {
      MessageBox::Show(S"Enumerating through the Hashtable collection");
      Enumerator = MyTable->GetEnumerator();

      while (Enumerator->MoveNext())
      {
      MessageBox::Show(Enumerator->Value->ToString());
      }
      }

      ICollection *MyKeys;

      if (MyTable->Count == 0)
      {
      MessageBox::Show(S"The hashtable is empty");
      }
      else
      {
      MessageBox::Show(S"Accessing keys property to return keys collection");
      MyKeys = MyTable->get_Keys();
      IEnumerator *Key = MyKeys->GetEnumerator();
      while(Key->MoveNext())
      {
      String *keyString = __try_cast<String *> (Key->Current);
      MessageBox::Show(keyString);
      }
      }
      This code declares a variable of type IDictionaryEnumerator and calls the GetEnumerator method of the Hashtable collection. After the code gets Enumerator, the code enumerates through the items in the collection and uses the Keys method of the Hashtable collection to enumerate through the keys.
  19. In the following steps, the Clear method is used to clear the Hashtable collection.
    1. Add a Button control to the Form1 form, and then change the Text property of the Button control to
      Clear.
    2. Double-click the button5 button, and then paste the following code in the button5_Click event.
      MyTable->Clear();
      MessageBox::Show(S"HashTable is now empty");
  20. Follow these steps to build and then run the application:
    1. Press CTRL+SHIFT+S to save the project.
    2. Press CTRL+SHIFT+B to build the solution.
    3. Press Ctrl + F5 to run the application.
    4. Click Add Items.

      Notice that three Person objects are added to the Hashtable collection.
    5. Click Get Items.

      Notice that the indexer obtains the items in the Hashtable collection. The three newly added items appear.
    6. Click Remove Item.

      Notice that the item at the "Burris" key location is deleted.
    7. Click Enumerate.

      Notice that the IDictionaryEnumerator interface enumerates through the items in the Hashtable collection, and the
      Keys property of the Hashtable collection returns a Keys collection.
    8. Click Clear.

      Notice that all the items are cleared from the Hashtable collection.
Note The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred.

back to the top
Propriedades

ID do Artigo: 815673 - Última Revisão: 7 de dez de 2007 - Revisão: 1

Comentários