'Can I add a different function that is defined in my code in a vector like arrays that include function adress?

In this code, there are 6 different functions. They create 6 different boards for playing a game. But I don't want to create boards with if conditions, I want to create a vector that includes function addresses in it. For example, if the user wants to create board 4 for playing the game, I want to create the board like this:

vector<vector<cell>> a = function_array[3];

cell is an enum type that I declared.

Can I do this, and can somebody help me for this?

vector<vector<cell>> first_table();
vector<vector<cell>> second_table();
vector<vector<cell>> third_table();
vector<vector<cell>> fourth_table();
vector<vector<cell>> fifth_table();
vector<vector<cell>> sixth_table();
    
int main()
{
    int chose,board_type;
    vector<vector<vector<cell>>> functions;

    functions.push_back(first_table());
    functions.push_back(second_table());
    functions.push_back(third_table()); //in here I create all boards and print which one the user wants
    functions.push_back(fourth_table()); //but I don't want to do this, I want just create the board the user wants
    functions.push_back(fifth_table());
    functions.push_back(sixth_table());

    vector<vector<cell>> b = functions[board_type-1];
    print_game(b);
    b = functions[0];
    cout << "welcomw Game" << endl;
    cout << "Please chose board type" << endl;
    cin >> board_type;
    int game_type;
    cout << "1.Personal game " << endl << "Computer game" << endl;
    cin >> game_type;
    string input;
    cout << "Please enter move direction" << endl;
    cin >> input;
}


Solution 1:[1]

What you are looking for is std::function

In your case, you'd create a vector of std::function<> for functions that take no parameter and return a vector<vector<cell>>.

#include <functional>
#include <vector>

struct cell {};

//type aliases make code a lot more readable!
using board = std::vector<std::vector<cell>>;

board first_table();
board second_table();
board third_table();
board fourth_table();
board fifth_table();
board sixth_table();

int main() {
  std::vector<std::function<board()>> functions;

  functions.push_back(first_table);
  // etc...

  board b = functions[board_type-1]();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Remy Lebeau