map 匹配字符串 调用相应函数
switch无法匹配字符串
基本语法:
switch (表达式) {
case 表达式1:
语句1;
break; //执行完语句1后,跳出switch语句,不执行剩下语句;
case 表达式2:
语句2;
//break; //如果没有break,则执行完语句2后,会继续执行下方的语句3
default:
语句3;
break;
}
'switch’只能用于等于判断, 用于int/char/long/long long
类型的变量,和多个特定常量的判断处理,不能用于 string/float
等类型的判断。
map简介
将字符串和类成员函数地址作为key值和value值传入map,再匹配字符串调用相应的函数。
定义
map的实现是一颗红黑树,map的内部键的数据都是排好序的,查找和删除、插入的效率都是lgN。map的本质其实就是映射,键值(key-value)一一对应。比如身份证号(key)和姓名(value)。
/*使用map需包含头文件`#include <map>`*/
#include <map>
/*定义*/
std::map <key_type, value_type> 变量名;
/*例子*/
std::map<int , string> test_map;
/*使用typedef简化*/
typedef std::map<int , string> TestMap;
TestMap test_map;
参考
CSDN:C++ STL Map的创建、删除、插入、更新、遍历
例子
#include <iostream>
#include <map>
#include <string>
using namespace std;
class Test
{
public:
Test();
void fun1(int a, int b)
{
cout << "fun1" << endl;
}
void fun2(int a, int b)
{
cout << "fun2" << endl;
}
/*传入函数名,执行对应的函数*/
void RunFunc(string funcName, int arg1, int arg2)
{
if (funcMap.count(funcName))
{
(this->*funcMap[funcName])(arg1, arg2);
}
}
private:
/*声明函数指针,作为map的value类型*/
typedef void (Test::*Fun_ptr)(int, int);
map<string, Fun_ptr> funcMap;
};
Test::Test()
{
/*将字符串和函数指针储存为pair类型,存入map*/
funcMap.insert(make_pair("fun1", &Test::fun1));
funcMap.insert(make_pair("fun2", &Test::fun2));
}
int main()
{
Test* pTest = new Test();
pTest->RunFunc("fun1", 1, 2);
pTest->RunFunc("fun2", 1, 2);
delete pTest;
pTest = nullptr;
system("pause");
return 0;
}
详解
定义类成员函数指针和map类型的变量,map变量的value值为类成员函数指针类型:
/*声明函数指针,作为map的value类型*/
typedef void (Test::*Fun_ptr)(int, int);
map<string, Fun_ptr> funcMap;
将字符串和类成员函数地址分别作为key和value存入map:
Test::Test()
{
/*将字符串和函数指针储存为pair类型,存入map*/
funcMap.insert(make_pair("fun1", &Test::fun1));
funcMap.insert(make_pair("fun2", &Test::fun2));
}
类内成员函数调用时,需要使用this指针,指明调用函数的对象;
if(funcMap.count(funcName))
用map的count方法判断key的出现次数,如果为0,则无法匹配上输入的字符串;为1则可以匹配上输入的字符串。
/*传入函数名,执行对应的函数*/
void RunFunc(string funcName, int arg1, int arg2)
{
if (funcMap.count(funcName))
{
(this->*funcMap[funcName])(arg1, arg2);
}
}
/**/