create vector of array of string and void function pointer in c++ [closed]
Solution 1:
You can take advantage of std::function
as below:
#include <iostream>
#include <functional>
void foofunc( )
{
// your code goes here
std::clog << "Hi" << '\n';
}
int main( )
{
std::function< void( ) > f_foofunc = foofunc;
f_foofunc( ); // call it directly
std::vector< std::pair< std::string, std::function<void( )> > > func_vec;
func_vec.push_back( { "foo", &foofunc } );
func_vec[0].second( ); // call it from the vector
}
Solution 2:
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.