首页 > 编程语言 > 详细

C++ map嵌套map

时间:2020-06-12 21:51:27      阅读:58      评论:0      收藏:0      [点我收藏+]

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

 

编译结果如下:

技术分享图片

C++ map嵌套map

原文:https://www.cnblogs.com/programer96s/p/13110350.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!