c++ - Using a map as "Phonebook" -
i have code similar this
enum days { monday, tuesday, wednesday, thursday, friday, saturday, sunday }; typedef void (*dailyfunction)(int); namespace dailyfunctions { void monday(int somedata); void tuesday(int somedata); void wednesday(int somedata); void thursday(int somedata); void friday(int somedata); void saturday(int somedata); void sunday(int somedata); } and somewere else in code use switch statement assign 1 of dailyfunctions dailyfunction ptr. when typing (more or less) same switch statement third time, had idea, great have map
std::map<days, dailyfunction> myphonebookmap which allow me this:
dailyfunction function_ptr = myphonebookmap[weekday]; to me seems, optimal place define such map in namespace dailyfunctions under function-declarations
but how can define const map there (since shouldnt change) , populate @ same time?
you can use boost function boost::assign::map_list_of or use copy constructor initialize const map constructed map:
#include <map> int main() { std::map<days, dailyfunction> m; m[ monday] = &monday; //... initialize m entries std::map<days, dailyfunction> const mc( m); //... return 0; }
Comments
Post a Comment