#include <stdio.h>
#include <map>
#include <string>
using namespace std;
// C++ affords PLENTY of mechanisms
// to make its code much less ugly.
// using namespace declarations,
// #defines and typedefs - but yet
// so many developers choose not
// to use these features and are
// perfectly content seeing lines
// of code like
// for( map::iterator iter = history.begin() ;iter != history.end(); ++iter )
// While it could look like
// foreach( HTIterType, iter, hash )
// I show how here.
int main()
{
typedef map Hashtable;
map history ;
history[ "first" ] = "bob" ;
history[ "second" ] = "mcnugget" ;
//string val = history[ "first" ];
//printf( "val is %s", val.c_str() );
for( map::iterator iter = history.begin() ;
iter != history.end();
++iter )
{
printf("key: %s / val: %s\n", iter->first.c_str() , iter->second.c_str() );
}
// Here's a more elegant way of doing that same thing
// Create a new type called Hashtable, which
// is going to be exactly equivalent to
// the map type
typedef map<string,string> Hashtable ;
// now define the HashtableIterator type
typedef map<string,string>::iterator HTIterType ;
// now create a hashtable
Hashtable hash ;
hash[ "firstentry" ] = "hello" ;
hash[ "another"] = "there" ;
// now use a "foreach" loop
#define foreach( x, y, z ) for( x y = z.begin(); y != z.end(); ++y )
// this is supposed to read "foreach ( HTIterType iter in hash )"
foreach( HTIterType, iter, hash )
{
printf("key: %s / val: %s\n", iter->first.c_str(), iter->second.c_str() );
}
// Because the #define above turns:
// foreach( HTIterType, iter, hash )
// into:
// for( HTIterType iter = hash.begin(); iter != hash.end(); ++iter )
// which is in turn equivalent to
// for( map::iterator iter = hash.begin(); iter != hash.end(); ++iter )
}