您好,登錄后才能下訂單哦!
1. 問題:
實現用字符串作為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函數,設置字符串的hash值,將字符串轉換為1個整數;
2、利用c++11自定義文字常量的語法,定義一個constexpr函數,switch的case標簽處調用這個constexpr函數。
3. 實現
1、定義一個hash函數,計算出字符串的hash值,將字符串轉換為1個整數;
定義: hash_map<const char*, int> CharHash;
struct CharLess : public binary_function<const char*, const char*, bool> { public: result_type operator()(const first_argument_type& _Left, const second_argument_type& _Right) const { return(stricmp(_Left, _Right) < 0 ? true : false); } }; |
然而,無論輸入任何字符串,都無法找到對應的整數值。因為輸入的字符串是指針,和"a"或"b"字符串常量指針的大小是絕對不會相同。解決方法如下:
寫一個仿函數CharLess,繼承自仿函數基類binary_function。
int main(int argc, const char** argv){ if (argc <= 1) cout << "input error ... " << endl; const char* strInput = argv[1]; hash_map<const char*, int, hash_compare<const char*, CharLess> > CharHash; 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函數,switch的case標簽處調用這個constexpr函數。
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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。