// ------- test-std2.cpp beg --------- // // Using STL, Standard Template Library for C++. // Testing hash_map (dictionary) datatype. // // This example is a reprint of // http://gcc.gnu.org/onlinedocs/libstdc++/faq/index.html#5_4 // http://www.icce.rug.nl/documents/cplusplus/cplusplus12.html // This is how to compile and run this code: // g++ -Wall test-std2.cpp -o test-std2 // ./test-std2 #include #include #include // For std::cin, std::out using namespace std; // Create namespace alias to reach the hash_map classes namespace stdext = ::__gnu_cxx; // This class' function operator() generates a hash value. // Unique hash values (indeces) provide quickest access to data. /* struct or */ class HashString { public: /*long*/ int operator()(std::string const &str) const { return stdext::hash()(str.c_str()); } }; // This class' function operator() tests if two keys are equal /* struct or */ class HashStringCompare { public: bool operator()(std::string s1, std::string s2) const { return s1 == s2; } }; // ------------------------------------------ int main() { // This hash_map dictionary will contain month names(=keys) and days(=values) stdext::hash_map 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 << "september -> " << months["september"] << endl << "april -> " << months["april"] << endl << "june -> " << months["june"] << endl << "november -> " << months["november"] << endl; // Ok return 0; } // ------- test-std2.cpp end ---------