Skip to content

Instantly share code, notes, and snippets.

@krysseltillada
Created June 29, 2015 23:33
Show Gist options
  • Save krysseltillada/5a6a97db742254236664 to your computer and use it in GitHub Desktop.
Save krysseltillada/5a6a97db742254236664 to your computer and use it in GitHub Desktop.
storing a number of functions in a vector and accessing them
#include <iostream> /// std::cout; std::endl;
#include <vector> /// std::vector;
int display (int, int);
int sum (int n1, int n2)
{
return n1 + n2;
}
int subtract (int n1, int n2)
{
return n1 - n2;
}
int multiply (int n1, int n2)
{
return n1 * n2;
}
int divide (int n1, int n2)
{
return n1 / n2;
}
int main()
{
std::vector<int (*)(int, int)> vec_func; /// equivalent to int (*vec_func) (int, int) that stores every pointed function in every element
vec_func.push_back(sum); /// equivalent to vec_func.push_back(&sum); --> automatic conversion to pointer when a function is pass by argument which is std::vector <int (*) (int, int)> vec_func;
vec_func.push_back(subtract); /// same as the upper comment
vec_func.push_back(multiply);
vec_func.push_back(divide);
std::vector<int (*) (int, int)>::iterator it = vec_func.begin(); /// denotes the 1st element for modified loop
for (unsigned i = 0; it != vec_func.end(); ++it, ++i)
std::cout << vec_func[i](22, 22) << std::endl; /// accessing every element and use them and displays the result
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment