c++ How can I make a std::vector of function pointers
To make a std::vector
of function pointers in C++, follow these steps:
- Declare a
typedef
for the function type you want to use as a function pointer. For example, if you want to create a vector of function pointers that take anint
parameter and returnvoid
, you can declare thetypedef
like this:
cpp
typedef void (*FunctionPtr)(int);
- Create a
std::vector
using the function pointer type. For example:
cpp
std::vector<FunctionPtr> functionPointers;
- Define your functions that match the function pointer type. For example:
```cpp void function1(int param) { // Function body }
void function2(int param) { // Function body } ```
- Add the function pointers to the vector using the address-of operator
&
. For example:
cpp
functionPointers.push_back(&function1);
functionPointers.push_back(&function2);
Here, &function1
and &function2
are the addresses of the functions function1
and function2
, respectively.
- You can now call the functions through the function pointers stored in the vector. For example:
cpp
functionPointers[0](42); // Calls function1 with parameter 42
functionPointers[1](10); // Calls function2 with parameter 10
The syntax functionPointers[index](parameter)
calls the function at the specified index with the given parameter.
That's it! You now have a std::vector
of function pointers in C++.