STL Examples


Map example 1: Rowset Object --
Basically a sorted dictionary. It can be traversed from either direction or used for lookups.

Note: this is an unsafe design; the next one is better.
#pragma warning( disable : 4786 )

#include <iostream>
#include <string>
#include <map>
using namespace std;
class ltstr
{
public:
   bool operator()(const char* s1, const char* s2) const
   {
      return strcmp(s1,s2) < 0;
   }
};

typedef map<const char*, string, ltstr> ROWSET;

void main(void)
{
   ROWSET InvoiceItem;
   InvoiceItem["Product"] = "Whole Wheat Bread";
   InvoiceItem["Units"]   = "100";
   InvoiceItem["Notes"]   = "Bag with twist tie";
   {
      string s = "Other";
      InvoiceItem[s.c_str()]   = "This will not work.";
      // the map defined with a key of const char* needs a static
      // variable for the string.  See the next example for a more.
      // robust version of this map definition.
   }
   
   cout << "Product     : " << InvoiceItem["Product"] << endl;
   cout << "Units       : " << InvoiceItem["Units"] << endl;
   cout << "Notes       : " << InvoiceItem["Notes"] << endl;
   cout << "Other       : " << InvoiceItem["Other"] << endl;

   cout << endl;
   cout << "Now dump the container in order..." << endl;

   ROWSET::iterator i;
   for (i=InvoiceItem.begin(); i != InvoiceItem.end(); i++ )
      cout << (*i).first << ": " << (*i).second << endl;
   // Note: the map doesn't have a reverse_iterator and rbegin()/rend()
   
   InvoiceItem.clear(); // clears all the entries
   if (InvoiceItem.empty())
      cout << "the map is empty." << endl;
}

Map Using string object as the Key
#pragma warning( disable : 4786 )

#include <iostream>
#include <string>
#include <map>
using namespace std;
class ltstr
{
public:
   bool operator()(const string s1, const string s2) const
   {
      return s1 < s2;
   }
};

typedef map<string, string, ltstr> ROWSET;

void main(void)
{
   ROWSET InvoiceItem;
   InvoiceItem["Product"] = "Whole Wheat Bread";
   InvoiceItem["Units"]   = "100";
   {
      string s = "Notes";
      InvoiceItem[s]   = "Bag with twist tie";
   }
   
   cout << "Product     : " << InvoiceItem["Product"] << endl;
   cout << "Units       : " << InvoiceItem["Units"] << endl;
   cout << "Notes       : " << InvoiceItem["Notes"] << endl;

   cout << endl;
   cout << "Now dump the container in order..." << endl;

   ROWSET::iterator i;
   for (i=InvoiceItem.begin(); i != InvoiceItem.end(); i++ )
      cout << (*i).first << ": " << (*i).second << endl;

   InvoiceItem.clear(); // clears all the entries
   if (InvoiceItem.empty())
      cout << "the map is empty." << endl;
}