C++11使用表格驱动技术替换switch case

来源:互联网 发布:网络名称大全5个字 编辑:程序博客网 时间:2024/06/09 21:27

当你使用switch case有很多种类时,往往代码写得非常长,如下:

 int main()

   {

         int i;

         i=1;

         switch(i)

         {

               case 1:

               printf("%d/n",i);

               break;

               case 2:

               printf("%d/n",i);

               break;

               case 3:

               printf("%d/n",i);

               break;

               case 4:

               printf("%d/n",i);

               break;

               deflaut:

               break;

         }

         return 1;

   } 


像这种,就可以使用C++11的功能,实现表格驱动的技术,如下:

#include "stdafx.h"#include <iostream>#include <functional>#include <memory>#include <map>class CTest{public:CTest(){//表格驱动技术代替switch casem_map[1] = [this](int x) {return Test1(x); };m_map[2] = [this](int x) {return Test2(x); };auto it = m_map.find(1);if (it != m_map.end())it->second(100);auto it1 = m_map.find(2);if (it1 != m_map.end())it1->second(108);}bool Test1(int a) { std::cout << "Test1 " << a << std::endl; return true; }bool Test2(int a) { std::cout << "Test2 " << a << std::endl; return true;}std::map<int, std::function<bool(int)>> m_map;};int main(){CTest test;    return 0;}

在这里主要使用function对象,它就可以很方便把一个函数变成一个对象保存起来。

深入浅出Numpy
http://edu.csdn.net/course/detail/6149 

Python游戏开发入门

http://edu.csdn.net/course/detail/5690

你也能动手修改C编译器

http://edu.csdn.net/course/detail/5582

纸牌游戏开发

http://edu.csdn.net/course/detail/5538 

五子棋游戏开发

http://edu.csdn.net/course/detail/5487
RPG游戏从入门到精通
http://edu.csdn.net/course/detail/5246
WiX安装工具的使用
http://edu.csdn.net/course/detail/5207
俄罗斯方块游戏开发
http://edu.csdn.net/course/detail/5110
boost库入门基础
http://edu.csdn.net/course/detail/5029
Arduino入门基础
http://edu.csdn.net/course/detail/4931
Unity5.x游戏基础入门
http://edu.csdn.net/course/detail/4810
TensorFlow API攻略
http://edu.csdn.net/course/detail/4495
TensorFlow入门基本教程
http://edu.csdn.net/course/detail/4369
C++标准模板库从入门到精通 
http://edu.csdn.net/course/detail/3324
跟老菜鸟学C++
http://edu.csdn.net/course/detail/2901
跟老菜鸟学python
http://edu.csdn.net/course/detail/2592
在VC2015里学会使用tinyxml库
http://edu.csdn.net/course/detail/2590
在Windows下SVN的版本管理与实战 
http://edu.csdn.net/course/detail/2579
Visual Studio 2015开发C++程序的基本使用 
http://edu.csdn.net/course/detail/2570
在VC2015里使用protobuf协议
http://edu.csdn.net/course/detail/2582
在VC2015里学会使用MySQL数据库
http://edu.csdn.net/course/detail/2672