最近的项目总使用到迭代器与map,随便写个例程增加熟练度
例程介绍:
通过Type与ID查询到指定函数进行相应操作;
#include <iostream>
#include <vector>
#include <string>
#include <map>
using std::string;
using std::vector;
using std::map;
enum class Test_Type:uint8_t
{
Type_non = 0,
Type_one,
Type_two,
};
enum class enumResult
{
NONE,
SUCCESS,
ERROR,
};
typedef enumResult (*pFun)(Test_Type Type, unsigned int id);
enumResult mapTest_func1(Test_Type Type, unsigned int id)
{
std::cout << "enter: " << __FUNCTION__ << std::endl;
std::cout << "Type: " << (unsigned int)Type << " ";
std::cout << "id: " << id << std::endl;
return enumResult::SUCCESS;
}
enumResult mapTest_func2(Test_Type Type, unsigned int id)
{
std::cout << "enter: " << __FUNCTION__ << std::endl;
std::cout << "Type: " << (unsigned int)Type << " ";
std::cout << "id: " << id << std::endl;
return enumResult::SUCCESS;
}
map<unsigned int, pFun> map_Type_one =
{
{0x0001, mapTest_func1},
{0x0002, mapTest_func2},
};
map<unsigned int, pFun> map_Type_two =
{
{0x0001, mapTest_func2},
{0x0002, mapTest_func1},
};
map<Test_Type, map<unsigned int, pFun>> map_find_Type =
{
{Test_Type::Type_one, map_Type_one},
{Test_Type::Type_two, map_Type_two},
};
void map_test(Test_Type Type, unsigned int id)
{
auto iterator_type = map_find_Type.find(Type);
if(iterator_type != map_find_Type.end())
{
auto iterator_id = iterator_type->second.find(id);
if(iterator_id != iterator_type->second.end())
{
/*can find function do something*/
iterator_id->second(Type, id);
}
else
{
std::cout << "not find id, please input again!" << std::endl;
return;
}
}
else{
std::cout << "not find Type, please input again!" << std::endl;
return;
}
}
int main()
{
while(1)
{
int Type = 0;
int id = 0;
std::cout << "**************test_menu*************" <<std::endl;
std::cout << "***1.Test_Type1 ***" <<std::endl;
std::cout << "***2.Test_Type2 ***" <<std::endl;
std::cin >> Type;
/*if(Test_Type::Type_one != (Test_Type)Type &&
Test_Type::Type_two != (Test_Type)Type)
{
std::cout << "num is error, please input anain!" << std::endl;
continue;
}*/
std::cout << "Please input id: " << std::endl;
std::cin >> id;
map_test((Test_Type)Type, id);
}
}
编译结果如下:
原文链接: https://www.cnblogs.com/programer96s/p/13110350.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/198774
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!