1

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.

1 Answers1

2

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;
}
sehe
  • 374,641
  • 47
  • 450
  • 633
mindriot
  • 5,413
  • 1
  • 25
  • 34
  • @Anamul If this answers your question, you can accept the answer. See https://stackoverflow.com/help/someone-answers. If your problem is still not solved, maybe you can clarify your original question. – mindriot May 17 '18 at 07:19