I am writing a date class where I want a static map to map "Jan" to 1 and so on. I am wondering how I can initialize that static map. This is what I am currently doing, but I just feel that the extra if statement is inelegant compared with static block in Java. I understand the compilation of C++ program is much more complicated, but I still wonder whether a better solution exists.
class date {
static map<string, int> month_map;
int month;
int year;
public:
class input_format_exception {};
date(const string&);
bool operator< (const date&) const;
string tostring() const;
};
map<string, int> date::month_map = map<string,int>();
date::date(const string& s) {
static bool first = true;
if (first) {
first = false;
month_map["Jan"] = 1;
month_map["Feb"] = 2;
month_map["Mar"] = 3;
month_map["Apr"] = 4;
month_map["May"] = 5;
month_map["Jun"] = 6;
month_map["Jul"] = 7;
month_map["Aug"] = 8;
month_map["Sep"] = 9;
month_map["Oct"] = 10;
month_map["Nov"] = 11;
month_map["Dec"] = 12;
}
// the rest code.
}
// the rest code.