您的位置:首页 > 编程语言 > C语言/C++

c++容器(vector|map)中使用函数指针

2014-03-07 17:13 357 查看
注意:容器中只能放类型,不能放函数指针变量名

// 声明一个函数指针

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_pInt;//不能这样定义,vector只能放类型,不能放函数指针变量名
vector<int(*)(int)> v_pInt;//正确,函数指针类型

    //vector<pInt> v_pInt;//正确

    v_pInt.push_back(&func1);//必须使用&

    v_pInt.push_back(&func2);

    int i = v_pInt[0](2);
cout<<i<<endl;//3

    i = v_pInt[1](2);
cout<<i<<endl;//22

    //

    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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐