You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何封装多段switch语句为通用函数?C++多分支逻辑复用咨询

封装支持动态分支数量的选择菜单函数(C++)

问题场景

现有两段高度重复的循环选择代码,分别包含3个和2个选项分支,每个分支对应不同的提示文本和执行函数。需要将这类选择逻辑封装为可复用函数,解决无法适配不同分支数量的问题。

原代码片段1:

while (1) {
    cout << "Enter the number corresponding to your choice:" << "\n";
    cout << "1 - Go North\n";
    cout << "2 - Go East\n";
    cout << "3 - Go West\n> ";
    cin >> choice;

    switch (choice){
      case 1:
        northAtlantic();
        break;
      case 2:
        southIndian();
        break;
      case 3:
        southPacific();
        break;
      default:
        cout << "Invalid choice. Try again.";
        pressEnter();
    }
  }

原代码片段2:

while (1) {
    cout << "Enter the number corresponding to your choice:" << "\n";
    cout << "1 - Go West\n";
    cout << "2 - Go South\n> ";
    cin >> choice;

    switch (choice){
      case 1:
        westArctic();
        break;
      case 2:
        westPacific();
        break;
      default:
        cout << "Invalid choice. Try again.";
        pressEnter();
    }
  }

解决方案

通过容器存储选项列表+可调用对象,实现通用的菜单函数,支持传入任意数量的选项文本和对应执行逻辑。

1. 定义选项结构体

用结构体封装每个选项的文本和对应的执行函数:

#include <iostream>
#include <vector>
#include <functional>
#include <limits>

// 假设pressEnter是已实现的等待回车函数
void pressEnter() {
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Press Enter to continue...";
    std::cin.get();
    std::cout << "\n";
}

// 选项结构体:存储提示文本和执行函数
struct MenuOption {
    std::string text;
    std::function<void()> action;
};

2. 实现通用菜单函数

编写可复用函数,处理循环、输入验证和执行逻辑:

void runMenu(const std::string& prompt, const std::vector<MenuOption>& options) {
    while (true) {
        // 打印提示与选项
        std::cout << prompt << "\n";
        for (size_t i = 0; i < options.size(); ++i) {
            std::cout << i + 1 << " - " << options[i].text << "\n";
        }
        std::cout << "> ";

        // 读取用户输入
        int choice;
        std::cin >> choice;

        // 输入合法性校验
        if (std::cin.fail() || choice < 1 || choice > static_cast<int>(options.size())) {
            std::cin.clear(); // 清除输入错误状态
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 丢弃无效输入
            std::cout << "Invalid choice. Try again.\n";
            pressEnter();
            continue;
        }

        // 执行对应选项的函数
        options[choice - 1].action();
    }
}

3. 调用示例

对应原两段代码的调用方式:

// 模拟原代码中的各个执行函数
void northAtlantic() { std::cout << "Going to North Atlantic!\n"; pressEnter(); }
void southIndian() { std::cout << "Going to South Indian!\n"; pressEnter(); }
void southPacific() { std::cout << "Going to South Pacific!\n"; pressEnter(); }
void westArctic() { std::cout << "Going to West Arctic!\n"; pressEnter(); }
void westPacific() { std::cout << "Going to West Pacific!\n"; pressEnter(); }

int main() {
    // 对应第一段代码的菜单
    std::vector<MenuOption> mainMenu = {
        {"Go North", northAtlantic},
        {"Go East", southIndian},
        {"Go West", southPacific}
    };
    // runMenu("Enter the number corresponding to your choice:", mainMenu);

    // 对应第二段代码的菜单
    std::vector<MenuOption> secondaryMenu = {
        {"Go West", westArctic},
        {"Go South", westPacific}
    };
    runMenu("Enter the number corresponding to your choice:", secondaryMenu);

    return 0;
}

优势说明

  • 完全支持动态数量的选项,适配任意分支数
  • 复用循环、输入验证逻辑,避免代码重复
  • 扩展性强,新增选项只需在vector中添加新的MenuOption即可

内容的提问来源于stack exchange,提问作者auden monteith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 11:55:26