Reputation: 15
I have a map where the key is a string and the value is a set of object Msg.
class Log{
std::map<std::string, std::set<Msg>> messages;
}
class Msg{
friend class Log;
std::string message;
std::chrono::system_clock::time_point timestamp;
}
The key is a phone number and the set contains objects with a text message from that number as well as the message's timestamp. I decided to use a set so that when I insert the messages, it will be sorted by its timestamp which is type time_point. The source is a text file of unsorted messages.
I wrote a comparison function for the set:
bool compareTimestamp(const Msg &lhs, const Msg &rhs){
return lhs.timestamp < rhs.timestamp;
}
From my research, if this were just a set and not a map of a set, to use the comparison function I would have to define the set like this
std::set<Msg, decltype(compareTimestamp)*> set;
and initialize the set in the constructor like this:
Log() : set(compareTimestamp){}
That worked when I tested it by inserting unsorted time_points.
However, I'm having trouble figuring out how to initialize the set with the comparison function inside of the map.
The map is defined in class Log like this:
std::map<std::string, std::set<Msg, decltype(compareTimepoint)*>> messages;
I tried to initialize this way but it's obviously wrong since it's initializing the map and not the set inside (I tested it anyway and it didn't work):
Log() : messages(compareTimepoint){}
Does anyone know how this can be done?
Upvotes: 0
Views: 1353
Reputation: 137780
Each set
has its own comparison function. The map
doesn't know about the functions of the set
s under it, or that those functions are all the same.
Since you don't plan to assign any other functions to the function pointer, you can use a comparison class instead. Such a class doesn't need initialization as a pointer does.
struct compareTimestamp {
bool operator () (const Msg &lhs, const Msg &rhs) const {
return lhs.timestamp < rhs.timestamp;
}
};
std::map<std::string, std::set<Msg, compareTimestamp>> messages;
Upvotes: 3