C++ map嵌套map

最近的项目总使用到迭代器与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);
    }
}

 

编译结果如下:

posted @ 2020-06-12 21:03  生而为人,学无止境  阅读(4250)  评论(0编辑  收藏  举报