C++测试Map和Vector实现函数的存储

来源:互联网 发布:ds video windows 编辑:程序博客网 时间:2024/06/05 16:19
#include <vector>
#include <map>
#include <string>

using namespace std;

// 声明一个函数指针
int(*pFunc)(int);
int func1(int nIn){return nIn + 1;}
int func2(int nIn){return nIn + 20;}

typedef int(*pInt)(int);//定义别名才能放在vector中

void main()
{
    pFunc = func1;// 把函数名赋给函数指针
    int n = pFunc(1);
    pFunc = &func2;
    n = pFunc(1);
    //vector<int(*pFun)(int)> v_pFunc;//不能这样定义
    
//
    vector<pInt> v_pInt;
    v_pInt.push_back(func1);
    v_pInt.push_back(func2);
    int i = v_pInt[0](2);
    i = v_pInt[1](2);
    //
    map<string,pInt> map_pInt;
    map_pInt.insert(pair<string,pInt>("key1",func1));
    map_pInt.insert(pair<string,pInt>("key2",func2));
    int j = map_pInt["key1"](3);
    j = map_pInt["key2"](3);
}
//之后作者有有一定修改
//vector只能放类型,不能放函数指针变量名
vector<int(*)(int)> v_pFunc;
v_pFunc.push_back(func1);
v_pFunc.push_back(func2);
int k = v_pFunc[0](5);
k = v_pFunc[1](5);
0 0
原创粉丝点击