1. 問題:
10年積累的網(wǎng)站制作、成都做網(wǎng)站經(jīng)驗(yàn),可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先網(wǎng)站策劃后付款的網(wǎng)站建設(shè)流程,更有姚安免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
實(shí)現(xiàn)用字符串作為switch語句的case子句。形如:
int main(int argc, const char** argv){ const char* strInput = argv[1]; switch(strInput){ case "first": cout << "first... " << endl; break; case "second": cout << "second... " << endl;; break; case "third": ccout << "third... " << endl; break; default: cout << "Default..." << endl; } } |
2. 基本思路
1、用hash函數(shù),設(shè)置字符串的hash值,將字符串轉(zhuǎn)換為1個整數(shù);
2、利用c++11自定義文字常量的語法,定義一個constexpr函數(shù),switch的case標(biāo)簽處調(diào)用這個constexpr函數(shù)。
3. 實(shí)現(xiàn)
1、定義一個hash函數(shù),計算出字符串的hash值,將字符串轉(zhuǎn)換為1個整數(shù);
定義: hash_map
struct CharLess : public binary_function { public: result_type operator()(const first_argument_type& _Left, const second_argument_type& _Right) const { return(stricmp(_Left, _Right) < 0 ? true : false); } }; |
然而,無論輸入任何字符串,都無法找到對應(yīng)的整數(shù)值。因?yàn)檩斎氲淖址侵羔?,?a"或"b"字符串常量指針的大小是絕對不會相同。解決方法如下:
寫一個仿函數(shù)CharLess,繼承自仿函數(shù)基類binary_function。
int main(int argc, const char** argv){ if (argc <= 1) cout << "input error ... " << endl; const char* strInput = argv[1]; hash_map CharHash["first"] = 0; CharHash["second"] = 1; CharHash["third"] = 2; if(CharHash.find(strInput) == CharHash.end()){ cout << "input error ... " << endl; return 0; } int nVal = CharHash[strInput]; switch(nVal){ case 0: cout << "first... " << endl; break; case 1: cout << "second..." << endl; break; case 2: cout << "third..." << endl; break; default: cout << "Default..." << endl; } } |
2、利用c++11自定義文字常量的語法,定義一個constexpr函數(shù),switch的case標(biāo)簽處調(diào)用這個constexpr函數(shù)。
constexpr hash_t hash_compile_time(char const* str, hash_t last_value = basis) { return *str ? hash_compile_time(str+1, (*str ^ last_value) * prime) : last_value; } |
可以寫出這樣的swich語句:
int main(int argc, const char** argv) { if (argc <= 1) cout << "input error ... " << endl; const char* str = argv[1]; switch(hash_(str)){ case hash_compile_time("first"): cout << " first " << endl; break; case hash_compile_time("second"): cout << " second " << endl; break; case hash_compile_time("third"): cout << " third " << endl; break; default: cout << "Default..." << endl; } } |
上面的語法還不夠漂亮,利用自定義文字常量,重載一個operator如下:
constexpr unsigned long long operator "" _hash(char const* p, size_t) { return hash_compile_time(p); } |
int main(int argc, const char** argv) { if (argc <= 1) cout << "input error ... " << endl; const char* str = argv[1]; switch(hash_(str)){ case "first"_hash: cout << " first " << endl; break; case " second"_hash: cout << " second " << endl; break; case " third"_hash: cout << " third " << endl; break; default: cout << "Default..." << endl; } } |
4. 參考資料
http://blog.csdn.net/yozidream/article/details/22789147
http://blog.csdn.net/sdhongjun/article/details/4517325