如何用比较函数初始化集合映射?

How to initialize a map of set with a comparison function?

我有一个映射,其中键是一个字符串,值是一组对象消息。

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;
}

密钥是一个 phone 号码,该集合包含带有来自该号码的文本消息的对象以及消息的时间戳。我决定使用一个集合,这样当我插入消息时,它会按类型为 time_point 的时间戳进行排序。来源是未分类消息的文本文件。

我为集合写了一个比较函数:

bool compareTimestamp(const Msg &lhs, const Msg &rhs){
return lhs.timestamp < rhs.timestamp;
}

根据我的研究,如果这只是一个集合而不是集合的映射,要使用比较函数,我必须像这样定义集合

std::set<Msg, decltype(compareTimestamp)*> set;

并像这样在构造函数中初始化集合:

Log() : set(compareTimestamp){}

当我通过插入未排序的 time_points 对其进行测试时,它起作用了。

但是,我无法弄清楚如何使用地图内部的比较函数来初始化集合。

地图定义在class 日志中是这样的:

std::map<std::string, std::set<Msg, decltype(compareTimepoint)*>> messages;

我试过用这种方式初始化,但显然是错误的,因为它初始化的是地图而不是里面的集合(无论如何我都测试过,但没有用):

Log() : messages(compareTimepoint){}

有谁知道如何做到这一点?

每个set都有自己的比较功能。 map不知道它下面的set的功能,或者那些功能都是一样的。

由于您不打算将任何其他函数分配给函数指针,因此可以使用比较 class 代替。这样的 class 不需要像指针那样进行初始化。

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;