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);
}
// 声明一个函数指针
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);
}
相关文章推荐
- c++容器(vector|map)中使用函数指针
- c++容器(vector|map)中使用函数指针
- C++ STL容器的学习使用(vector、queue、list、set、map)
- C++中防止STL中迭代器失效——map/set等关联容器——vector/list/deque等序列容器—如何防止迭代器失效—即erase()的使用
- C++ STL基本容器的使用(vector、list、deque、map、stack、queue)
- C++中防止STL中迭代器失效__map/set等关联容器vector/list/deque等序列容器_如何防止迭代器失效_即erase()的使用
- 【语言-C++】C++容器:list、vector、hash、map的区别及使用范围
- C++中防止STL中迭代器失效__map/set等关联容器vector/list/deque等序列容器_如何防止迭代器失效_即erase()的使用
- C++中防止STL中迭代器失效——map/set等关联容器——vector/list/deque等序列容器—如何防止迭代器失效—即erase()的使用
- C++ STL容器的使用方法(vector、queue、list、set、map)
- C++文本查询程序 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- C++中map容器的说明和使用技巧
- c++编写无向图 使用容器Vector编写邻接表法
- 使用C++STL的map容器实现一种命令映射
- C++中的哈希容器unordered_map使用示例
- 使用C++容器vector实现的两路归并排序
- 使用C++的map容器遇到的bug(map/set iterator not dereferencable)
- C++各个容器比较(vector,deque,list,set,map,queue,stack)
- C++文本查询程序 不要定义类和智能指针管理数据 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- C++ vector容器类型使用