function call in another function parameter

Is there a way to send a function as a parameter of another function. Basically my idea was to have a loop function thats only job is to loop a container, and then send in a function of what to do with each element upon that loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>
#include <string>
#include <map>

class Deck{
    public:
        
        std::vector<int> suit_num = {2,3,4,5,6,7,8,9,10,11,12,13,14};
        std::vector<std::string> suit_name = {"spades", "clubs", "hearts", "diamonds"};
        std::map<std::string, std::vector<int>> cards;
        Deck(){
            for (auto name: suit_name){
                cards.insert(std::pair<std::string, std::vector<int>>(name, suit_num));
            }
        }
        
        void loop(){
            std::string num_display;
            for (auto name: suit_name){
                for (auto num: cards[name]){
                    if (num == 11)
                        num_display = "Jack";
                    else if (num == 12)
                        num_display = "Queen";
                    else if (num == 13)
                        num_display = "King";
                    else if (num == 14)
                        num_display = "Ace";
                    else
                        num_display = std::to_string(num);
                    std::cout << num_display << ' ' << name << ", ";
                }
                std::cout << "\n\n";
            }
        }
};


int main(){
    Deck deck;

    deck.loop();
}


so as where it is hard coded currently in Deck::loop() to just display the contents, would there be a way to send a function in to do something else with the elements? as to avoid string arguments associated with if conditions to do specific tasks?
Last edited on
You can use a function pointer.

http://www.cplusplus.com/doc/tutorial/pointers/
(Example at very bottom of that page)
Topic archived. No new replies allowed.