使用map实现函数的switch-case

    #include <iostream>  
    #include <iterator>  
    #include <string>  
    #include <map>  

    using namespace std;  

    // 函数指针定义  
    typedef void (* switchcallback)(void);  

    void displayA() {  
        cout << "Aaaaa" << endl;  
    }  

    void displayB() {  
        cout << "Bbbbb" << endl;  
    }  

    void displayC() {  
        cout << "Ccccc" << endl;  
    }  

    int main() {  
        map <string,switchcallback> stringMap;  
        stringMap.insert(pair<string,switchcallback>("Aaaaa",displayA));  
        stringMap.insert(pair<string,switchcallback>("Bbbbb",displayB));  
        stringMap.insert(pair<string,switchcallback>("Ccccc",displayC));  

        map<string,switchcallback>::iterator stringMapItr;  

        stringMapItr = stringMap.find("Ccccc");  
        stringMapItr->second();  


        return 0;  
    }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++中使用字符串hash函数加switch可以实现快速的字符串匹配,可以避免使用if-else语句进行逐个比对,从而提高程序的效率。具体实现步骤如下: 1. 定义字符串hash函数,将字符串转化为一个整数,可以使用STL中的hash函数或自己实现一个hash函数。 2. 在switch语句中使用hash值进行匹配,每个case语句匹配一个特定的hash值,从而实现字符串的匹配。 示例代码如下: ```c++ #include <iostream> #include <string> #include <functional> using namespace std; // 定义字符串hash函数 struct StrHash { size_t operator()(const string& str) const { return hash<string>()(str); } }; int main() { unordered_map<size_t, string> map = { {hash<string>()("hello"), "Hello World!"}, {hash<string>()("world"), "World Hello!"}, {hash<string>()("good"), "Good Morning!"}, {hash<string>()("night"), "Good Night!"} }; string str; cout << "Please enter a string: "; getline(cin, str); // 使用字符串hash值进行匹配 switch (hash<string>()(str)) { case hash<string>()("hello"): cout << map[hash<string>()("hello")] << endl; break; case hash<string>()("world"): cout << map[hash<string>()("world")] << endl; break; case hash<string>()("good"): cout << map[hash<string>()("good")] << endl; break; case hash<string>()("night"): cout << map[hash<string>()("night")] << endl; break; default: cout << "Unknown input!" << endl; break; } return 0; } ``` 注意:使用字符串hash函数加switch时,需要保证hash函数的唯一性,否则可能会出现hash冲突,导致匹配错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值