Search code examples
c++arrayspointersvectorstd

c++: storing some structured data containing diffrent datatypes in a single entity


i a bunch of enumerte data which are a name and a function (pointer to it) related to function. how to store them in a single entity for example an array or vector

i want something like this in python:

a = [["foo",foofunc]["bar",barfunk]]

or this in js:

let a = {}
a["foo"] = foofunc

it doesn't matters if name and the function are not at the same level. i just want the function to be accessible through the name.


Solution

  • I think you're looking for a vector of pair<std::string, void (*)() as shown below:

    
    #include <iostream>
    #include <utility>
    #include <string>
    #include <vector>
    void foofunc()
    {
        std::cout<<"foofunc called"<<std::endl;
        //do something here 
    }
    void barfunc()
    {
        std::cout<<"barfunc called"<<std::endl;
        //do something here 
    }
    int main()
    {
        //create a vector of pair of std::string and pointer to function with no parameter and void return type
        std::vector<std::pair<std::string, void (*)()>> a;
        
        //add elements into the vector
        a.push_back({"foo", &foofunc});
        a.push_back({"bar", &barfunc});
        
        //lets try calling the functions inside the vector of pairs
        a[0].second();//calls foofunc()
        
        a[1].second(); //calls barfunc()
        return 0;
    }
    

    The output of the above program can be seen here.