Hashtable |
This is a complete hash table with it's own iterator. It provides a fast and well-tested hash function that can be over-ridden. All features associated with a hash table are implemented.
Note: Template T must provide a
method (member function) with the following signature
operator const char* (void) const;
This method is used to obtain a char* to pass to the hashing
function.
If a hash function is provided, it
must take one parameter: "const char*" and return an
"int". The value returned must be a positive integer or zero.
Otherwise the underlying array will throw an Exception.
The following is an example using hashtable
#include <ospace/advanced/Hash.h>
#include <ospace/std/iostream>
// When STL string is member of a class, such as person in this example,
// we simply overload the conversion operator to char* for the class itself.
// The STL string is used as is.
class person
{
public:
person( );
person(string, short);
person(const person&);
person& operator=(const person&);
operator const char* (void) const {return name.c_str();}
short Age(void) {return age;}
void setAge(short a) {age = a;}
private:
string name;
short age;
};
person::person(void) : name()
{
age = 0;
}
person::person(string n, short a) : name(n)
{
age = a;
}
person::person(const person& p) : name(p.name)
{
age = p.age;
}
person& person::operator=(const person& p)
{
if (*this != p)
{
name = p.name;
age = p.age;
}
return *this;
}
// Inserting multiple copies of an item with same key, in Hash table. Finding
// number of insertions, and navigating among items with same key.
int main()
{
os_Hash<person> personTable;
person P("John", 39);
personTable << P; // insert in table
P.setAge(44);
personTable << P;
P.setAge(21);
personTable << P;
P.setAge(87);
personTable << P;
// Last item inserted in table is at top. Get attributes of last item.
if (personTable.entity("John").Age() == 87)
cout << "Last person inserted was 87 years old." << endl;
else
cout << "Last person inserted was NOT 87 years old." << endl;
// Get the number of items with same key.
int num = personTable.number("John");
cout << "There are " << num << " persons named John" << endl;
// Important. Counting begins at 1 (not 0) and proceeds like stack. So,
// first person inserted will be at bottom, in this case 4th item.
person& pr = personTable.Member("John", num);
cout << "First person named John was " << pr.Age() << " years old." << endl;
return 0;
}
Copyright©2005-2026 Recursion
Software LLC
All Rights Reserved - For use by licensed users only.