Friday, March 23, 2012

Hash template in C++

 

#include <map>
#include <iostream>
#include <cstring>

using namespace std;

struct eqstr {
    bool operator() (const char *s1, const char *s2) const {
   return (::strcmp(s1, s2) < 0 ? true : false);
 }
};


int main()
{
 // template 
    map <const char *, int, eqstr> months;

    months["january"] = 31;
    months["february"] = 28;
    months["march"] = 31;
    months["april"] = 30;
    months["may"] = 31;
    months["june"] = 30;
    months["july"] = 31;
    months["august"] = 31;
    months["september"] = 30;
    months["october"] = 31;
    months["november"] = 30;
    months["december"] = 31;

    cout << "february -> " << months["february"] << endl;
    cout << "september -> " << months["september"] << endl;
    cout << "april     -> " << months["april"] << endl;
    cout << "july      -> " << months["july"] << endl;
    cout << "november  -> " << months["november"] << endl;

 for(map::iterator it=months.begin();
     it != months.end(); it++)
 {
  cout << (*it).first << " => " << (*it).second << endl;
 }
}

No comments:

Post a Comment