C++中如何用std::unordered_map实现消息key到处理函数的映射调用
优化方案
你可以通过std::function定义统一的消息处理函数类型,再用std::unordered_map建立key和处理函数的映射关系,同时将重复的校验、错误打印逻辑抽成公共模块,减少冗余代码。
具体实现步骤:
- 引入
<unordered_map>和<functional>头文件 - 定义统一的处理函数类型别名
- 初始化key到处理函数的映射表
- 收到消息后直接通过key查表调用对应函数即可
完整参考代码:
#include <iostream> #include <string> #include <unordered_map> #include <functional> // 定义统一的消息处理函数类型:入参为消息值,无返回值 using MsgHandler = std::function<void(const std::string&)>; // 示例处理函数,可替换为实际业务逻辑 void fun1(const std::string& val) { std::cout << "处理key1消息,内容:" << val << std::endl; } void fun2(const std::string& val) { std::cout << "处理key2消息,内容:" << val << std::endl; } void fun3(const std::string& val) { std::cout << "处理key3消息,内容:" << val << std::endl; } void fun4(const std::string& val) { std::cout << "处理key4消息,内容:" << val << std::endl; } void fun5(const std::string& val) { std::cout << "处理key5消息,内容:" << val << std::endl; } // 公共校验逻辑,可替换为实际校验规则 bool validate_msg(const std::string& msg) { // 示例默认返回合法,可根据业务需求修改 return true; } int main() { // 初始化key到处理函数的映射表,后续新增key仅需在此添加配置 std::unordered_map<std::string, MsgHandler> handler_map = { {"key1", fun1}, {"key2", fun2}, {"key3", fun3}, {"key4", fun4}, {"key5", fun5} }; char buff[2048]; ssize_t data_len; while (true) { // 保留原有网络接收逻辑即可 // ssize_t recv_ret = recv(sockfd, buff, sizeof(buff), 0); // 接收错误/断开逻辑可自行补充 // data_len = recv_ret; std::string msg(buff, data_len); std::string::size_type pos = msg.find_first_of(","); if (pos == std::string::npos) { std::cerr << "Invalid data: " << __FILE__ << ", " << __PRETTY_FUNCTION__ << ", " << __LINE__ << "\n"; continue; } std::string key = msg.substr(0, pos); // 查表匹配处理函数 auto it = handler_map.find(key); if (it == handler_map.end()) { std::cerr << "Unknown msg key: " << key << ", " << __FILE__ << ", " << __PRETTY_FUNCTION__ << ", " << __LINE__ << "\n"; continue; } // 公共校验 if (!validate_msg(msg)) { std::cerr << "Invalid data: " << __FILE__ << ", " << __PRETTY_FUNCTION__ << ", " << __LINE__ << "\n"; continue; } // 提取参数调用对应处理函数 std::string val = msg.substr(pos + 1); it->second(val); } return 0; }
优化说明
- 查表时间复杂度从原有的O(n)降到O(1),消息key数量越多性能提升越明显
- 新增消息类型仅需新增处理函数+在映射表加一行配置,无需修改主流程逻辑,可维护性更高
- 重复的校验、错误打印逻辑统一抽离,代码冗余度大幅降低
内容的提问来源于stack exchange,提问作者Harry
相关产品推荐
相关产品推荐

