Pass member function as a argument

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
typedef bool compF(int, int);
typedef priority_queue<int, vector<int>, function<bool(int,int)>> mypq_type;

class Node {
    public:
     bool end=false;
     unordered_map<char,int> next;
     mypq_type pq;
     int sp=-1;

     Node(function<bool(int,int)> comparator) : pq ((comparator)){}
};

class Trie {
    public:
     vector<Node*> tr;
     vector<int>& times;
     vector<string>& sentences;

     Trie(vector<string>& sentences, vector<int>& times): times(times), sentences(sentences){
         tr.push_back(new Node(&comparator));
     }
    
     bool comparator(int a, int b) {
         if (times[a] != times[b]) {
            return a > b;
        }

        return sentences[a].compare(sentences[b]) < 0 : true: false;
     }
    
    void insert(string& s,int i) {
        int p=0;
        vector<char> nS;
        for(char ch: s) {
            if (tr[p]->next.find(ch) == tr[p]->next.end()) {
                tr[p]->next[ch]=tr.size();
                tr.emplace_back(new Node(&comparator));
            }
} 


In places like tr.push_back(new Node(&comparator)); tr.emplace_back(new Node(&comparator));
Error: must explicitly qualify name of member function when taking its address
Initially tried passing just "comparator" function without &
Got this
reference to non-static member function must be called
tr.push_back(new Node(comparator));

Last edited on
Members are a pain to pass around because they don't make much sense without the object pointer too.

This used to be my goto page for this area some years back.
https://www.parashift.com/c++-faq/pointers-to-members.html
minimum (but far from best) fix is probably to bind your member comparator to this using std::bind:
tr.push_back(new Node(bind(&Trie::comparator, this, _1, _2)));
live demo https://wandbox.org/permlink/0VMz7sfeagi3Bn9S

(I tried to keep the rest intact, but "sentences[a].compare(sentences[b]) < 0 : true: false" didn't compile so it was replaced with sentences[a] < sentences[b])
Last edited on
Topic archived. No new replies allowed.