Ask coding questions

← Back to all posts
How to make a vector that runs functions?
Typhlotion (1)

Title says it all. I'm new to C++ and wanted to make a vector of functions to make my text based game work better. Would there be any way to make that work (or make a system where you can swap out several functions for one another)? Right now my code just gives me a wall of errors because I was stupid enough to make a vector of voids, but I think it's a pretty good example of what I'm trying to get working.
Thanks in advance, sorry if my code is atrocious.

Answered by ANDREWVOSS (187) [earned 5 cycles]
View Answer
Comments
hotnewtop
ANDREWVOSS (187)
typedef void (*function)();
std::vector<function> = {punch,chargingKicks,weakHeal}
Typhlotion (1)

@ANDREWVOSS I tried this solution and named the vector "functions" and although it didn't give out a wall of errors, it still doesn't actually run the functions. What do I have to do to make it work?

ANDREWVOSS (187)

@Typhlotion I was a bit wrong. it should look like

typedef void (*function)();
std::vector<function> moves = {punch,chargingKicks,weakHeal}; // To set up the vector
moves[playerInput](); // To call a function
Typhlotion (1)

@ANDREWVOSS That definitely did it. Thanks