本文整理汇总了C++中Hashtable::Put方法的典型用法代码示例。如果您正苦于以下问题:C++ Hashtable::Put方法的具体用法?C++ Hashtable::Put怎么用?C++ Hashtable::Put使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Hashtable
的用法示例。
在下文中一共展示了Hashtable::Put方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: setbad
void Texture::setbad( const string & s)
{
// Put both current path+texfile and shared texfile since they both have been looked for
bool * b = new bool( true);
if( VSFileSystem::current_path.back()!="")
badtexHashTable.Put( VSFileSystem::GetHashName(s), b);
badtexHashTable.Put( VSFileSystem::GetSharedTextureHashName(s), b);
}
示例2: main
// This program exercises the Ref class.
int main(void)
{
CompleteSetupSystem setupSystem;
printf("sizeof(TestItemRef)=%i\n", (int)sizeof(TestItemRef));
{
printf("Checking queue...\n");
Queue<TestItemRef> q;
printf("Adding refs...\n");
for (int i=0; i<10; i++)
{
char temp[50]; muscleSprintf(temp, "%i", i);
TestItemRef tr(new TestItem(temp));
ConstTestItemRef ctr(tr);
ConstTestItemRef t2(ctr);
q.AddTail(tr);
}
printf("Removing refs...\n");
while(q.HasItems()) q.RemoveHead();
printf("Done with queue test!\n");
}
{
printf("Checking hashtable\n");
Hashtable<String, TestItemRef> ht;
printf("Adding refs...\n");
for (int i=0; i<10; i++)
{
char temp[50]; muscleSprintf(temp, "%i", i);
ht.Put(String(temp), TestItemRef(new TestItem(temp)));
}
printf("Removing refs...\n");
for (int i=0; i<10; i++)
{
char temp[50]; muscleSprintf(temp, "%i", i);
ht.Remove(String(temp));
}
printf("Done with hash table test!\n");
}
printf("Beginning multithreaded object usage test...\n");
{
const uint32 NUM_THREADS = 50;
TestThread threads[NUM_THREADS];
for (uint32 i=0; i<NUM_THREADS; i++) threads[i].StartInternalThread();
Snooze64(SecondsToMicros(10));
for (uint32 i=0; i<NUM_THREADS; i++) threads[i].ShutdownInternalThread();
printf("Multithreaded object usage test complete.\n");
}
printf("testrefcount complete, bye!\n");
return 0;
}
示例3: colShield
collideTrees::collideTrees( const std::string &hk, csOPCODECollider *cT,
csOPCODECollider *cS ) : hash_key( hk )
, colShield( cS )
{
for (unsigned int i = 0; i < collideTreesMaxTrees; ++i)
rapidColliders[i] = NULL;
rapidColliders[0] = cT;
refcount = 1;
unitColliders.Put( hash_key, this );
}
示例4: GetFactionIndex
/**
* Returns the relationship between myfaction and theirfaction
* 1 is happy. 0 is neutral (btw 1 and 0 will not attack)
* -1 is mad. <0 will attack
*/
int FactionUtil::GetFactionIndex( const string& name )
{
static Hashtable< string, int, 47 >factioncache;
int *tmp = factioncache.Get( name );
if (tmp)
return *tmp;
int i = GetFactionLookup( name.c_str() );
tmp = new int;
*tmp = i;
factioncache.Put( name, tmp );
return i;
}
示例5: modold
void Texture::modold (const string &s, bool shared, string & hashname) {
hashname = shared?VSFileSystem::GetSharedTextureHashName(s):VSFileSystem::GetHashName(s);
Texture * oldtex = new Texture;
// oldtex->InitTexture();new calls this
oldtex->name=-1;
oldtex->refcount=1;
oldtex->original=NULL;
oldtex->palette=NULL;
oldtex->data=NULL;
texHashTable.Put(hashname, oldtex);
original = oldtex;
}
示例6: LogTime
StdinDataIO :: StdinDataIO(bool blocking, bool writeToStdout)
: _stdinBlocking(blocking)
, _writeToStdout(writeToStdout)
#ifdef USE_WIN32_STDINDATAIO_IMPLEMENTATION
, _slaveSocketTag(0)
#else
, _fdIO(ConstSocketRef(&_stdinSocket, false), true)
#endif
{
#ifdef USE_WIN32_STDINDATAIO_IMPLEMENTATION
if (_stdinBlocking == false)
{
// For non-blocking I/O, we need to handle stdin in a separate thread.
// note that I freopen stdin to "nul" so that other code (read: Python)
// won't try to muck about with stdin and interfere with StdinDataIO's
// operation. I don't know of any good way to restore it again after,
// though... so a side effect of StdinDataIO under Windows is that
// stdin gets redirected to nul... once you've created one non-blocking
// StdinDataIO, you'll need to continue accessing stdin only via
// non-blocking StdinDataIOs.
bool okay = false;
ConstSocketRef slaveSocket;
if ((CreateConnectedSocketPair(_masterSocket, slaveSocket, false) == B_NO_ERROR)&&(SetSocketBlockingEnabled(slaveSocket, true) == B_NO_ERROR)&&(_slaveSocketsMutex.Lock() == B_NO_ERROR))
{
bool threadCreated = false;
if (_stdinThreadStatus == STDIN_THREAD_STATUS_UNINITIALIZED)
{
DWORD junkThreadID;
#if __STDC_WANT_SECURE_LIB__
FILE * junkFD;
#endif
_stdinThreadStatus = ((DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_INPUT_HANDLE), GetCurrentProcess(), &_stdinHandle, 0, false, DUPLICATE_SAME_ACCESS))&&
#if __STDC_WANT_SECURE_LIB__
(freopen_s(&junkFD, "nul", "r", stdin) == 0)
#else
(freopen("nul", "r", stdin) != NULL)
#endif
&&((_slaveThread = (::HANDLE) _beginthreadex(NULL, 0, StdinThreadEntryFunc, NULL, CREATE_SUSPENDED, (unsigned *) &junkThreadID)) != 0)) ? STDIN_THREAD_STATUS_RUNNING : STDIN_THREAD_STATUS_EXITED;
threadCreated = (_stdinThreadStatus == STDIN_THREAD_STATUS_RUNNING);
}
if ((_stdinThreadStatus == STDIN_THREAD_STATUS_RUNNING)&&(_slaveSockets.Put(_slaveSocketTag = (++_slaveSocketTagCounter), slaveSocket) == B_NO_ERROR)) okay = true;
else LogTime(MUSCLE_LOG_ERROR, "StdinDataIO: Could not start stdin thread!\n");
_slaveSocketsMutex.Unlock();
// We don't start the thread running until here, that way there's no chance of race conditions if the thread exits immediately
if (threadCreated) ResumeThread(_slaveThread);
}
else LogTime(MUSCLE_LOG_ERROR, "StdinDataIO: Error setting up I/O sockets!\n");
if (okay == false) Close();
}
#endif
}
示例7: TestIteratorSanityOnRemoval
static void TestIteratorSanityOnRemoval(bool backwards)
{
LogTime(MUSCLE_LOG_INFO, "Testing iterator sanity (direction=%s)\n", backwards?"backwards":"forwards");
static const uint32 COUNT = 100;
for (uint32 i=0; i<COUNT; i++)
{
Hashtable<int32, int32> table;
for (uint32 j=0; j<COUNT; j++) table.Put(j, j+COUNT);
uint32 numPairsFound = 0;
int32 prevKey = backwards ? (int32)COUNT : -1;
LogTime(MUSCLE_LOG_DEBUG, " Beginning traversal...\n");
for(HashtableIterator<int32,int32> iter(table, backwards?HTIT_FLAG_BACKWARDS:0); iter.HasData(); iter++)
{
int32 expectedKey = (backwards?(prevKey-1):(prevKey+1));
int32 gotKey = iter.GetKey();
int32 gotValue = iter.GetValue();
LogTime(MUSCLE_LOG_TRACE, " Iter returned " INT32_FORMAT_SPEC" -> " INT32_FORMAT_SPEC"\n", iter.GetKey(), iter.GetValue());
if (gotKey != expectedKey)
{
LogTime(MUSCLE_LOG_CRITICALERROR, "Expected key=" INT32_FORMAT_SPEC", got key=" INT32_FORMAT_SPEC" (value=" UINT32_FORMAT_SPEC")\n", expectedKey, gotKey, gotValue);
ExitWithoutCleanup(10);
}
if ((gotKey%(i+1))==0) {LogTime(MUSCLE_LOG_TRACE, " -> Deleting key=" INT32_FORMAT_SPEC"\n", gotKey); table.Remove(gotKey);}
numPairsFound++;
prevKey = gotKey;
}
if (numPairsFound != COUNT)
{
LogTime(MUSCLE_LOG_CRITICALERROR, "Expected to iterate across " UINT32_FORMAT_SPEC" pairs, only saw " UINT32_FORMAT_SPEC"!\n", COUNT, numPairsFound);
ExitWithoutCleanup(10);
}
}
}
示例8: LoadString
PyCodeObject *CompilePython (const std::string &name) {
Python::reseterrors();
PyCodeObject * retval = compiled_python.Get (name);
Python::reseterrors();
if (retval) {
return retval;
}
char * str = LoadString (name.c_str());
if (str) {
fprintf(stdout,"Compiling python module %s\n",name.c_str());
std::string compiling_name = getCompilingName(name).c_str();
char * temp = strdup(compiling_name.c_str());
retval = (PyCodeObject *) Py_CompileString (str,temp,Py_file_input);
if (retval) {
compiled_python.Put(name,retval);
}
free (temp);
free (str);
}
return retval;
}
示例9: main
// This program exercises the Hashtable class.
int main(int argc, char ** argv)
{
CompleteSetupSystem css;
Message temp; if (ParseArgs(argc, argv, temp) == B_NO_ERROR) HandleStandardDaemonArgs(temp);
if (temp.HasName("inter")) return DoInteractiveTest();
// Make sure that setting equal to an empty Hashtable clears the buffer (FogBugz #10274)
{
Hashtable<String,String> table;
for (int32 i=0; i<1000; i++) table.Put(String("xxx%1").Arg(i), "foo");
printf("After population of " UINT32_FORMAT_SPEC " items, table size is " UINT32_FORMAT_SPEC "\n", table.GetNumItems(), table.GetNumAllocatedItemSlots());
if (table.ShrinkToFit() == B_NO_ERROR) printf("After shrink-to-fit, table allocation is " UINT32_FORMAT_SPEC " for " UINT32_FORMAT_SPEC " items\n", table.GetNumAllocatedItemSlots(), table.GetNumItems());
else printf("Shrink-to-fit failed!?\n");
printf("Before copy-from-empty, table allocation is " UINT32_FORMAT_SPEC "\n", table.GetNumAllocatedItemSlots());
table = GetDefaultObjectForType< Hashtable<String,String> > ();
printf(" After copy-from-empty, table allocation is " UINT32_FORMAT_SPEC "\n", table.GetNumAllocatedItemSlots());
}
// Test C++11 move semantics to make sure they aren't stealing
{
String key = "key";
String value = "value";
Hashtable<String,String> table;
table.Put(key, value);
if (key != "key") {printf("ERROR, Hashtable stole my key!\n"); exit(10);}
if (value != "value") {printf("ERROR, Hashtable stole my value!\n"); exit(10);}
}
// Test muscleSwap()
TestMuscleSwap<Hashtable<String,String> >("Hashtable");
TestMuscleSwap<OrderedKeysHashtable<String,String> >("OrderedKeysHashtable");
TestMuscleSwap<OrderedValuesHashtable<String,String> >("OrderedValuesHashtable");
// Test iterator behaviour when deleting keys
TestIteratorSanityOnRemoval(false);
TestIteratorSanityOnRemoval(true);
{
LogTime(MUSCLE_LOG_INFO, "Testing a keys-only Hashtable value...\n");
Hashtable<int, Void> keysOnly;
printf("sizeof(keysOnly)=%u\n", (unsigned int) sizeof(keysOnly));
keysOnly.PutWithDefault(1);
keysOnly.PutWithDefault(2);
keysOnly.PutWithDefault(5);
keysOnly.PutWithDefault(10);
for (HashtableIterator<int, Void> iter(keysOnly); iter.HasData(); iter++) printf("key=%i\n", iter.GetKey());
}
{
LogTime(MUSCLE_LOG_INFO, "Testing Tuple as a Hashtable key...\n");
// A quick test of the Tuple class as a Hashtable key
typedef Tuple<2,int> MyType;
Hashtable<MyType, int> tupleTable;
MyType a; a[0] = 5; a[1] = 6;
MyType b; b[0] = 7; b[1] = 8;
tupleTable.Put(a, 1);
tupleTable.Put(b, 2);
for (HashtableIterator<MyType, int> iter(tupleTable); iter.HasData(); iter++)
{
const MyType & key = iter.GetKey();
printf("key=%i,%i val=%i\n", key[0], key[1], iter.GetValue());
}
int * ra = tupleTable.Get(a);
int * rb = tupleTable.Get(b);
printf("tuple: ra=[%i] rb=[%i]\n", ra?*ra:666, rb?*rb:666);
}
{
LogTime(MUSCLE_LOG_INFO, "Testing Rect as a Hashtable key...\n");
// A quick test of the Tuple class as a Hashtable key
Hashtable<Rect, int> tupleTable;
Rect a(1,2,3,4);
Rect b(5,6,7,8);
tupleTable.Put(a, 1);
tupleTable.Put(b, 2);
for (HashtableIterator<Rect, int> iter(tupleTable); iter.HasData(); iter++)
{
const Rect & key = iter.GetKey();
printf("key=%f,%f,%f,%f val=%i\n", key.left(), key.top(), key.right(), key.bottom(), iter.GetValue());
}
int * ra = tupleTable.Get(a);
int * rb = tupleTable.Get(b);
printf("Rect: ra=[%p] rb=[%p]\n", ra, rb);
}
{
LogTime(MUSCLE_LOG_INFO, "Testing Point as a Hashtable key...\n");
// A quick test of the Tuple class as a Hashtable key
Hashtable<Point, int> tupleTable;
//.........这里部分代码省略.........
示例10: main
// This program is equivalent to the portableplaintext client, except
// that we communicate with a child process instead of a socket.
int main(int argc, char ** argv)
{
CompleteSetupSystem css;
if (argc < 3) PrintUsageAndExit();
const uint32 numProcesses = atol(argv[1]);
if (numProcesses == 0) PrintUsageAndExit();
const char * cmd = argv[2];
Hashtable<String,String> testEnvVars;
(void) testEnvVars.Put("Peanut Butter", "Jelly");
(void) testEnvVars.Put("Jelly", "Peanut Butter");
(void) testEnvVars.Put("Oranges", "Grapes");
Queue<DataIORef> refs;
for (uint32 i=0; i<numProcesses; i++)
{
ChildProcessDataIO * dio = new ChildProcessDataIO(false);
refs.AddTail(DataIORef(dio));
printf("About To Launch child process #" UINT32_FORMAT_SPEC ": [%s]\n", i+1, cmd); fflush(stdout);
ConstSocketRef s = (dio->LaunchChildProcess(argc-2, ((const char **) argv)+2, ChildProcessLaunchFlags(MUSCLE_DEFAULT_CHILD_PROCESS_LAUNCH_FLAGS), NULL, &testEnvVars) == B_NO_ERROR) ? dio->GetReadSelectSocket() : ConstSocketRef();
printf("Finished Launching child process #" UINT32_FORMAT_SPEC ": [%s]\n", i+1, cmd); fflush(stdout);
if (s() == NULL)
{
LogTime(MUSCLE_LOG_CRITICALERROR, "Error launching child process #" UINT32_FORMAT_SPEC " [%s]!\n", i+1, cmd);
return 10;
}
}
StdinDataIO stdinIO(false);
PlainTextMessageIOGateway stdinGateway;
QueueGatewayMessageReceiver stdinInputQueue;
stdinGateway.SetDataIO(DataIORef(&stdinIO, false));
SocketMultiplexer multiplexer;
for (uint32 i=0; i<refs.GetNumItems(); i++)
{
printf("------------ CHILD PROCESS #" UINT32_FORMAT_SPEC " ------------------\n", i+1);
PlainTextMessageIOGateway ioGateway;
ioGateway.SetDataIO(refs[i]);
ConstSocketRef readSock = refs[i]()->GetReadSelectSocket();
QueueGatewayMessageReceiver ioInputQueue;
while(1)
{
int readFD = readSock.GetFileDescriptor();
multiplexer.RegisterSocketForReadReady(readFD);
const int writeFD = ioGateway.HasBytesToOutput() ? refs[i]()->GetWriteSelectSocket().GetFileDescriptor() : -1;
if (writeFD >= 0) multiplexer.RegisterSocketForWriteReady(writeFD);
const int stdinFD = stdinIO.GetReadSelectSocket().GetFileDescriptor();
multiplexer.RegisterSocketForReadReady(stdinFD);
if (multiplexer.WaitForEvents() < 0) printf("testchildprocess: WaitForEvents() failed!\n");
// First, deliver any lines of text from stdin to the child process
if ((multiplexer.IsSocketReadyForRead(stdinFD))&&(stdinGateway.DoInput(ioGateway) < 0))
{
printf("Error reading from stdin, aborting!\n");
break;
}
const bool reading = multiplexer.IsSocketReadyForRead(readFD);
const bool writing = ((writeFD >= 0)&&(multiplexer.IsSocketReadyForWrite(writeFD)));
const bool writeError = ((writing)&&(ioGateway.DoOutput() < 0));
const bool readError = ((reading)&&(ioGateway.DoInput(ioInputQueue) < 0));
if ((readError)||(writeError))
{
printf("Connection closed, exiting.\n");
break;
}
MessageRef incoming;
while(ioInputQueue.RemoveHead(incoming) == B_NO_ERROR)
{
printf("Heard message from server:-----------------------------------\n");
const char * inStr;
for (int i=0; (incoming()->FindString(PR_NAME_TEXT_LINE, i, &inStr) == B_NO_ERROR); i++) printf("Line %i: [%s]\n", i, inStr);
printf("-------------------------------------------------------------\n");
}
if ((reading == false)&&(writing == false)) break;
multiplexer.RegisterSocketForReadReady(readFD);
if (ioGateway.HasBytesToOutput()) multiplexer.RegisterSocketForWriteReady(writeFD);
}
if (ioGateway.HasBytesToOutput())
{
printf("Waiting for all pending messages to be sent...\n");
while((ioGateway.HasBytesToOutput())&&(ioGateway.DoOutput() >= 0)) {printf ("."); fflush(stdout);}
}
}
printf("\n\nBye!\n");
//.........这里部分代码省略.........
示例11: main
int main(int argc, char ** argv)
{
CompleteSetupSystem css;
PrintExampleDescription();
Hashtable<String, int> table;
// If we know up-front a limit on the number of items we are likely to place
// into the table, we can reserve that many slots in advance, and thereby
// avoid any chance of the Hashtable having to reallocate its internal array
// while we are adding items to it.
//
// That avoids some inefficiency, and it also means we don't have
// to worry about out-of-memory errors, or the memory-locations of key or
// value-items changing, while populating the table.
if (table.EnsureSize(20) != B_NO_ERROR) WARN_OUT_OF_MEMORY;
// Put some initial data into the table
table.Put("One", 1);
table.Put("Two", 2);
// table.GetWithDefault() returns a reference to the value of the specified
// key, or a reference to a default-constructed value otherwise.
const int & oneRef = table.GetWithDefault("One");
const int & twoRef = table.GetWithDefault("Two");
const int & threeRef = table.GetWithDefault("Three");
printf("A: OneRef=%i twoRef=%i threeRef=%i\n", oneRef, twoRef, threeRef);
printf("\n");
// The [] operator is a synonym for GetWithDefault()
printf("B: table[\"One\"]=%i table[\"Two\"]=%i table[\"Three\"]=%i\n", table["One"], table["Two"], table["Three"]);
printf("\n");
// GetOrPut() returns a pointer to the value of the given key, if the key is present
// If the key isn't present, it places a key/value pair into the Hashtable and returns
// a pointer to the (default-constructed) placed value. This is very useful when
// demand-allocating records.
int * pEight = table.GetOrPut("Eight");
printf("C: table.GetOrPut(\"Eight\") returned %p\n", pEight);
if (pEight) *pEight = 8;
else WARN_OUT_OF_MEMORY; // GetOrPut() returns NULL only on memory-exhaustion
printf("\n");
// The next time we call GetOrPut() we'll get a pointer to the existing value
pEight = table.GetOrPut("Eight");
printf("C: Second call to table.GetOrPut(\"Eight\") returned %p (aka %i)\n", pEight, pEight?*pEight:666);
printf("\n");
// We can also call GetOrPut() with a suggested default-value which will be
// placed into the key/value pair if the supplied key isn't already present.
int * pNine = table.GetOrPut("Nine", 9);
printf("C: table.GetOrPut(\"Nine\", 9) returned %p (aka %i)\n", pNine, pNine?*pNine:666);
printf("\n");
// PutAndGet() is similar to GetOrPut() except it *always* places a value.
// (if the key already existed in the table, its value will be overwritten)
int * pTen = table.PutAndGet("Ten", 10);
printf("D: table.PutAndGet(\"Ten\", 10) returned %p (aka %i)\n", pTen, pTen?*pTen:666);
// Demonstrate PutAndGet()'s overwrite of the previous value
pTen = table.PutAndGet("Ten", 11);
printf("E: table.PutAndGet(\"Ten\", 11) returned %p (aka %i)\n", pTen, pTen?*pTen:666);
// If you want a Hashtable with keys only and don't need values at all
// (similar to e.g. a std::unordered_set<>), a good way to get that is
// to use the Void class as your value-type. A Void object is just a
// placeholder that contains no data.
Hashtable<String, Void> keysOnlyTable;
(void) keysOnlyTable.PutWithDefault("Blue");
(void) keysOnlyTable.PutWithDefault("Red");
(void) keysOnlyTable.PutWithDefault("Green");
printf("\n");
return 0;
}
示例12: AddStarsystemToUniverse
void StarSystem::AddStarsystemToUniverse( const string &mname )
{
star_system_table.Put( mname, this );
}
示例13: main
int main()
{
ScreenManager::GetInstance().SetText("Testing");
ScreenManager::GetInstance().DrawText();
Material* quartz = new Material((char*)"Quartz", false, false);
Material* granite = new Material((char*)"Granite", false, false);
Clock* clock = new Clock();
World* world = new World();
SolarSystem* solar = new SolarSystem();
// name, mass, diameter (mi), radius (mi), surf gravity (m/s2)
solar->Add(new Star((char*)"Sun", MASS(1.989,30), 864337.3, 432169, 274));
solar->Add(new Planet((char*)"Mercury", MASS(3.285,23), 3032, 1516, 3.7));
solar->Add(new Planet((char*)"Venus", MASS(4.867,24), 7520.8, 3760, 8.87));
solar->Add(new Planet((char*)"Earth", MASS(5.972,24), 7917.5, 3959, 9.807));
solar->Add(new Planet((char*)"Mars", MASS(6.39,23), 4212, 2106, 3.711));
solar->Add(new Planet((char*)"Jupiter", MASS(1.898,27), 86881.4, 43441, 24.79));
solar->Add(new Planet((char*)"Saturn", MASS(5.683,26), 72367.4, 36184, 10.44));
solar->Add(new Planet((char*)"Uranus", MASS(8.681,25), 31518, 15759, 8.87));
solar->Add(new Planet((char*)"Neptune", MASS(1.024,26), 30599, 15299, 11.15));
// name mass diameter (mi)radius (mi)surf gravity (m/s2)
Planet* earth = new Planet( (char*)"Earth", MASS(5.972,24), 7917.5, 3959, 9.807);
Satellite* moon = new Satellite( (char*)"Moon", MASS(7.347,22), 2159, 1079, 1.62);
earth->Add(moon);
solar->Add(earth);
sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "Game");
window.setFramerateLimit(60);
srand(time(0));
sf::CircleShape shape(100.f);
shape.setFillColor(sf::Color::Green);
Hashtable hash;
hash.Put("Test","Test2");
int one = 1;
hash.Put("one", &one);
printf("Hashtable %s %d",(char *)hash.Get("Test"), *(int *)hash.Get("one"));
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
clock->Update();
window.clear();
window.draw(shape);
window.display();
}
Engine egnine;
return 0;
}
示例14: main
/* This little program demonstrates the semantics of the keys used in a Hashtable */
int main(int argc, char ** argv)
{
CompleteSetupSystem css;
PrintExampleDescription();
// In order to use a type as a Key in a Hashtable, that type must have
// two properties: There must be a way to compute a hash-code for any
// give Key object, and it must be possible to compare two Key objects
// for equality (using the == operator).
//
// If you want to call SortByKey() or use the type as a key in an
// OrderedKeysHashtable, the < operator must also be defined for the type.
// For primitive/POD key types, the Hashtable class uses SFINAE
// magic so that Hashtables with those keys will automatically "just work".
// For example:
Hashtable<int, String> tableWithIntKeys; // works!
Hashtable<uint16, String> tableWithUint16Keys; // works!
Hashtable<uint32, String> tableWithUint32Keys; // works!
Hashtable<int32, String> tableWithInt32Keys; // works!
Hashtable<char, String> tableWithCharKeys; // works!
Hashtable<float, String> tableWithFloatKeys; // works! (but probably a bad idea!)
// When using a "Proper class" as a Key type, you'll want to make
// sure it has a working == operator and that it has a method
// like this one defined:
//
// uint32 HashCode() const;
//
// This method should return a 32-bit value based on the object's
// current state; that value will be used to place the key/value
// pair within the Hashtable's array.
Hashtable<MyKeyClass, int> myTable;
(void) myTable.Put(MyKeyClass(12, 23), 0);
(void) myTable.Put(MyKeyClass(21, 22), 5);
(void) myTable.Put(MyKeyClass(37, 19), 6);
printf("myTable's contents are:\n");
for (HashtableIterator<MyKeyClass, int> iter(myTable); iter.HasData(); iter++)
{
printf(" [%s] -> %i\n", iter.GetKey().ToString()(), iter.GetValue());
}
printf("\n");
// Test retrieving a value using a MyKeyClass object as the key
int retVal;
if (myTable.Get(MyKeyClass(21, 22), retVal) == B_NO_ERROR)
{
printf("myTable.Get(MyKeyClass(21, 22) retrieved a key with value %i\n", retVal);
}
else printf("myTable.Get(MyKeyClass(21, 22) failed!\n");
// You can even use pointers-to-objects as your keys as long as
// the pointed-to-objects can be used as keys. The pointer-keys
// will generally work the same as the value-keys, but note that
// you are responsible for making sure the pointers remain valid
// for the lifetime of the Hashtable!
String s1 = "One";
String s2 = "Two";
String s3 = "Three";
Hashtable<String *, int> ptrTable;
ptrTable.Put(&s1, 1);
ptrTable.Put(&s2, 2);
ptrTable.Put(&s3, 3);
printf("\n");
printf("ptrTable's contents are:\n");
for (HashtableIterator<String *, int> iter(ptrTable); iter.HasData(); iter++)
{
printf(" %s -> %i\n", iter.GetKey()->Cstr(), iter.GetValue());
}
printf("\n");
// Refs can also be used as keys, if, you're in to that sort of thing.
// Here's a Hashtable with ConstSocketRefs as keys!
Hashtable<ConstSocketRef, Void> sockTable;
for (int i=0; i<10; i++) sockTable.PutWithDefault(CreateUDPSocket());
printf("sockTable's contents are:\n");
for (HashtableIterator<ConstSocketRef, Void> iter(sockTable); iter.HasData(); iter++)
{
const Socket * s = iter.GetKey()();
printf(" socket descriptor #%i\n", s ? s->GetFileDescriptor() : -1);
}
printf("\n");
return 0;
}