如何用比较函数初始化set的映射

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

本文关键字:set 映射 初始化 函数 何用 比较      更新时间:2023-10-16

我有一个映射,其中键是字符串,值是对象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;
}

键是一个电话号码,集合包含带有该号码的文本消息以及消息的时间戳的对象。我决定使用一个集合,这样当我插入消息时,它将按照时间戳(类型为time_point)进行排序。源文件是未排序消息的文本文件。

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

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

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

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

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

Log() : set(compareTimestamp){}

当我通过插入未排序的时间点进行测试时,它工作了。

但是,我不知道如何用map内部的比较函数初始化集合。

映射在Log类中定义如下:

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

我尝试以这种方式初始化,但它显然是错误的,因为它初始化映射,而不是里面的集合(我测试了它,无论如何,它没有工作):

Log() : messages(compareTimepoint){}

有谁知道这是怎么做的吗?

每个set都有自己的比较函数。map不知道其下set s的功能,也不知道这些功能都是相同的。

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

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;