如何用比较函数初始化set的映射
How to initialize a map of set with a comparison function?
我有一个映射,其中键是字符串,值是对象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;
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- 在类中使用映射并通过其他类的 get() 和 set() 函数访问值
- 如何在C++中迭代集合映射(std::map<std::set< char>, int >)?
- 如何在std :: Map中找到std :: set中的映射中的最小/最大值
- map/set迭代器不可递增,我无法从头开始重新启动映射
- 如何在 std::map 中使用 emplace(),其值为 std::set(从某物映射到集合)
- "map/set iterators incompatible"映射销毁,取决于构造函数调用
- 如何在std::set中获得给定下界和上界的映射中的值范围?
- 将映射转换为STL中的set
- std::set相对于向量或映射的优点
- 如何从set初始化映射
- 如何用比较函数初始化set的映射
- 如何在C++中迭代集合(std::map<string,std::set< string> >)的映射?
- Map /set迭代器不可解引用.多映射容器