Functor question

hi guys from this tutorial https://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html

I don't understand how it works,I mean he is passing _field to the getHeader but he is comparing the same string because field will be the same right?

it's hard to explain but field will be the same variable in the message sorter class and we are sending _field as the argument so aren't we just comparing the same string to the same string?

also he doesn't actually implement the getHeader function.
That code is kind of screwed up. He's also creating the "comparator" variable without a parameter even though there's no default ctor. Try this:

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
45
46
47
48
49
50
51
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

class Message {
public:
    Message(string title, string time) : title(title), time(time) {}
    string getHeader (const string& header_name) const {
        if (header_name == "title")
            return title;
        if (header_name == "time")
            return time;
        return "";
    }
    friend ostream& operator<<(ostream& os, const Message& m);
private:
    string title;
    string time;
};

ostream& operator<<(ostream& os, const Message& m) {
    return os << m.title << ", " << m.time << '\n';
}
 
class MessageSorter {
public:
    MessageSorter (const string& field) : _field( field ) {}
    bool operator() (const Message& lhs, const Message& rhs) {
        return lhs.getHeader( _field ) < rhs.getHeader( _field );
    }
private:
    string _field;
};

int main() {
    vector<Message> messages;
    messages.push_back(Message("hello", "12345"));
    messages.push_back(Message("abacus", "54321"));
    messages.push_back(Message("zebra", "22222"));

    MessageSorter compare_time("time");
    sort(messages.begin(), messages.end(), compare_time);
    for (const auto& x: messages) cout << x;
    cout << '\n';

    MessageSorter compare_title("title");
    sort(messages.begin(), messages.end(), compare_title);
    for (const auto& x: messages) cout << x;
}

Last edited on
I think the idea is that different messages can have different headers for the same field. In the example on how to use it he forgot to pass the field that he wanted to sort by to the MessageSorter constructor.

1
2
3
// Sort messages by their "From:" header fields.
MessageSorter comparator("From");
sort(messages.begin(), messages.end(), comparator);
thanks tpb :) yeah that does look clearer

and thanks Peter good spot that does make more sense now
Topic archived. No new replies allowed.