1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
struct Person
{
string m_fname;
string m_lname;
Person (string fname, string lname) : m_fname (fname), m_lname (lname) {}
bool operator == (const Person& rhs) const
{
return (m_fname == rhs.m_fname && m_lname == rhs.m_lname);
}
};
ostream& operator << (ostream& os, const Person& p)
{
os<<"First name: "<<p.m_fname<<", Last name: "<<p.m_lname<<"\n";
return os;
}
namespace std {
template <> //in this case legal to specialize template inside std namespace
struct hash<Person>
{
size_t operator()(const Person& p) const
{
// Compute individual hash values for m_fname, m_lname and combine them using XOR and bit shifting:
return ((hash<string>()(p.m_fname) ^ (hash<string>()(p.m_lname) << 1)) >> 1);
}
};
}
/*struct PersonHasher //alternatively define hash function as a separate struct and add it to the template argument list for the map;
{
size_t operator()(const Person& p) const
{
return ((hash<string>()(p.m_fname)
^ (hash<string>()(p.m_lname) << 1)) >> 1);
};
};*/
struct Expenditure
{
string m_date;
string m_item;
double m_amount;
Expenditure (string date, string item, double amount) : m_date (date), m_item (item), m_amount (amount) {}
};
ostream& operator << (ostream& os, const Expenditure& e)
{
os<<"Date: "<<e.m_date<<" - Item: "<<e.m_item<<", Amount: "<<e.m_amount<<"\n";
return os;
}
int main()
{
unordered_map <Person, Expenditure> persExp =
{
{Person("John", "Smith"), Expenditure("12/01/16", "Books", 55)},
{Person("Jane", "Doe"), Expenditure("12/02/16", "Travel", 6500)},
};
//below using hash function as separate class
/*unordered_map <Person, Expenditure, PersonHasher> persExp =
{
{Person("John", "Smith"), Expenditure("12/01/16", "Books", 55)},
{Person("Jane", "Doe"), Expenditure("12/02/16", "Travel", 6500)},
};*/
for(auto& elem : persExp)
{
cout<<elem.first;
cout<<elem.second;
}
}
|