How to use unordered_map in which gregorian_date
will be used as a key ?
unordered_map<boost::gregorian::date,int>date_map;
boost::gregorian::date sample_date{2018,01,01};
date_map[sample_date]=1;
Can any one please help me.
How to use unordered_map in which gregorian_date
will be used as a key ?
unordered_map<boost::gregorian::date,int>date_map;
boost::gregorian::date sample_date{2018,01,01};
date_map[sample_date]=1;
Can any one please help me.
Your question is closely related to unordered_map with gregorian dates, except you are using a std::unordered_map
instead of the boost::unordered_map
. You need to solve the same problem: If you want to use any data type as a key in an unordered_map
, you need to provide a specialization of std::hash
for that type (in your case ::boost::gregorian::date
). Building on the answer given for the question I linked, you can use this specialization:
#include <boost/date_time/gregorian/gregorian.hpp>
#include <unordered_map>
namespace std {
// Note: This is pretty much the only time you are allowed to
// declare anything inside namespace std!
template <>
struct hash<boost::gregorian::date>
{
size_t operator () (const boost::gregorian::date& date) const
{
return std::hash<decltype(date.julian_day())>()(date.julian_day());
}
};
}
int main()
{
std::unordered_map<boost::gregorian::date, int> date_map;
boost::gregorian::date sample_date{2018, 1, 1};
date_map[sample_date] = 1;
}