Deleting an Item
To delete an element, it first needs to be found.
Dictionary_Delete does this using
Dictionary_FindIndex, which you saw previously:
int Dictionary_Delete( IDictionary *p, const char *szKey )
{
CDictionary *pMe = DICTIONARY_FROM_INTERFACE( p );
uint32 index = 0;
int result = EBADPARM;
if ( !pMe || !szKey || STRLEN( szKey ) == 0 ) return result;
result = Dictionary_FindIndex( pMe, szKey, &index );
if ( result == SUCCESS )
{
if ( pMe->pfnDeallocator && pMe->pElements[ index ].pValue )
{
(pMe->pfnDeallocator)(pMe->pElements[ index ].pValue);
}
pMe->pElements[ index ].pValue = NULL;
FREE( pMe->pElements[ index ].szKey );
pMe->pElements[ index ].szKey = NULL;
pMe->pElements[ index ].hash = 0;
pMe->consumed--;
}
return result;
}
After validating its arguments, the routine finds the index of the key in question, and if it's found, uses the dictionary's deallocator to free the item. Next, it nulls the pointer to the item and frees the key, nulling the key as well to indicate the slot is empty and available for reuse. Finally, the hash is set to zero.
Dictionary_DeleteAll does the same, but across all set elements in the dictionary's collection.
Useful and Reusable
Using Brew's component-oriented approach makes it easy to create reusable data structures that you can share between your applications. Dictionaries and vectors benefit greatly from this approach because they can be foundation collection in many applications and share a common conceptual interface. Feel free to leverage these in your own applications!