c++ map容器 与 函数指针或者类成员函数指针

本文聚焦信息技术领域,介绍了map容器的使用,重点阐述了如何在map容器中放入普通函数指针和类成员函数指针,还给出了C++ map用法总结及函数指针相关的参考链接。

本文主要介绍 map容器中如何放入函数指针和类成员函数指针。

一、map容器的使用:

// 定义一个map对象
     map<int, string> mapStudent;
     
  参考:https://blog.youkuaiyun.com/sevenjoin/article/details/81943864

二、map容器与普通函数指针

#include "map"
#include "string"
#include "vector"
#include "iostream"

void Func1(int a){
    std::cout <<"func1: "<< a<<std::endl;
}
void Func2(int a){
    std::cout <<"func2: "<< a<<std::endl;
}
void Func3(int a){
    std::cout <<"func3: "<< a<<std::endl;
}

int main(int argc, char** argv){
    std::map<std::string, void(*)(int)> Func = {
            {"name1", Func1},
            {"name2", Func2},
            {"name3", Func3}
        };
    
    Func["name2"](5);  
    return 0;
}

三、map容器与类成员函数指针

#include "map"
#include "string"
#include "vector"
#include "iostream"

class TestPointer{
public:
    TestPointer() = default;
    ~TestPointer() = default;
    void Run(){
        (this->*func_map["name2"])(5);
    }
private:
    void Test1(int a){
        std::cout<<"test1: "<<a<<std::endl;
    }
    void Test2(int a){
        std::cout<<"test2: "<<a<<std::endl;
    }
private:
    typedef void(TestPointer::*pTest)(int);
    std::map<std::string, pTest> func_map = {
            {"name1", &TestPointer::Test1},
            {"name2", &TestPointer::Test2}
        };
};


int main(int argc, char** argv){
    TestPointer test;
    test.Run();
   
    return 0;
}

参考:

C++ map用法总结(整理):https://blog.youkuaiyun.com/sevenjoin/article/details/81943864

详解函数指针和类成员函数指针: https://blog.youkuaiyun.com/yyx112358/article/details/78515420

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值