用字符串数组代替switch+case
时间: 2023-11-23 22:56:23 浏览: 42
可以使用字典来代替switch+case语句,将每个case对应的操作作为字典的value,将case作为字典的key,然后通过输入的字符串来获取对应的操作。以下是一个示例代码:
```python
def case1():
print("This is case 1")
def case2():
print("This is case 2")
def case3():
print("This is case 3")
# 定义字典
switcher = {
"case1": case1,
"case2": case2,
"case3": case3
}
# 获取输入的字符串
input_str = input("请输入case名称:")
# 通过字典获取对应的操作
func = switcher.get(input_str, lambda: "Invalid case")
print(func())
```
在上面的代码中,我们定义了三个函数case1、case2和case3,然后将它们作为字典的value,将case1、case2和case3作为字典的key,最后通过输入的字符串获取对应的操作。如果输入的字符串不在字典中,则返回"Invalid case"。
相关问题
如何用字符串数组代替switch case
当需要根据不同的条件执行不同的操作时,通常可以使用switch case语句。但是,如果条件较多或者需要频繁修改条件,使用字符串数组代替switch case可以更加灵活和易于维护。
以下是使用字符串数组代替switch case的一种常见方法:
1. 创建一个字符串数组,数组的每个元素表示一个条件。
2. 创建一个与字符串数组对应的函数指针数组,数组的每个元素表示一个操作函数。
3. 根据输入的条件,在字符串数组中查找对应的索引。
4. 使用索引在函数指针数组中找到对应的操作函数,并执行。
下面是一个示例代码:
```cpp
#include <iostream>
#include <functional>
#include <string>
void operation1() {
std::cout << "执行操作1" << std::endl;
}
void operation2() {
std::cout << "执行操作2" << std::endl;
}
void operation3() {
std::cout << "执行操作3" << std::endl;
}
int main() {
std::string conditions[] = {"condition1", "condition2", "condition3"};
std::function<void()> operations[] = {operation1, operation2, operation3};
std::string inputCondition;
std::cout << "请输入条件:" << std::endl;
std::cin >> inputCondition;
int index = -1;
for (int i = 0; i < sizeof(conditions) / sizeof(conditions[0]); i++) {
if (inputCondition == conditions[i]) {
index = i;
break;
}
}
if (index != -1) {
operations[index]();
} else {
std::cout << "条件不存在" << std::endl;
}
return 0;
}
```
在上述示例中,我们使用字符串数组`conditions`存储条件,使用函数指针数组`operations`存储对应的操作函数。根据输入的条件,在`conditions`中查找对应的索引,然后使用索引在`operations`中找到对应的操作函数,并执行。
使用函数指针数组代替Switch Case
当我们需要根据不同的输入值执行不同的操作时,常用的方式是使用Switch Case语句,但是当需要判断的情况较多时,Switch Case语句的代码量会较大,可读性也有所下降。此时,可以使用函数指针数组来代替Switch Case语句,代码会更加简洁、易读。
下面是一个使用函数指针数组代替Switch Case的示例:
```c
#include <stdio.h>
void func1() { printf("You chose option 1.\n"); }
void func2() { printf("You chose option 2.\n"); }
void func3() { printf("You chose option 3.\n"); }
int main() {
int option;
void (*func_ptr_arr[])(void) = {func1, func2, func3};
printf("Enter an option (1-3): ");
scanf("%d", &option);
if (option >= 1 && option <= 3) {
(*func_ptr_arr[option-1])();
} else {
printf("Invalid option.\n");
}
return 0;
}
```
在上面的示例中,我们首先定义了三个函数`func1()`、`func2()`和`func3()`,分别对应三个选项。然后,我们定义了一个函数指针数组`func_ptr_arr`,它包含了三个函数指针,分别指向三个函数。
在主函数中,我们首先读取用户输入的选项,然后判断选项是否合法。如果合法,就通过函数指针数组调用对应的函数。如果不合法,则输出错误信息。
需要注意的是,函数指针数组中的函数指针要与函数的返回类型和参数列表完全匹配。在调用函数指针时,我们使用了函数指针的间接调用操作符`*`,并且在函数名后面加上了一对小括号`()`,这表示对函数指针所指向的函数进行调用。
使用函数指针数组代替Switch Case语句可以使代码更加简洁、易读,而且可以方便地添加、修改和删除选项。