Boost序列化映射与比较器
Boost serialize map with comparator
有人能帮助我了解如何序列化地图与比较器。保存后,map知道比较器类,但是map不知道比较器字段。
bool operator() (const ScalarT &a, const ScalarT &b) const{
return (a - someField < b);
}
啊。非常好的问题。这是boost中序列化的一个限制。
如果是有状态比较器,则不序列化比较器状态。
在SSCCE中演示这个问题:Live On Coliru,它打印
====== original order
3 -> three
2 -> two
1 -> one
====== deserialized order
1 -> one
2 -> two
3 -> three
这是有意义的,因为否则将要求所有比较器都是可序列化的。这带来了困难的问题(如果Cmp是std::function<bool(K)>
怎么办?如果实际值是一个lambda呢?
所以,长话短说:咬紧牙关,也序列化你的比较器:
Live On Coliru
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/map.hpp>
#include <iostream>
#include <sstream>
template <typename T>
struct StateFullCmp {
bool invert_;
StateFullCmp(bool invert) : invert_(invert) {}
bool operator()(T const&a, T const& b) const {
return invert_? (b<a) : (a<b);
}
};
namespace boost { namespace serialization {
template <typename Ar, typename T>
void serialize(Ar& ar, StateFullCmp<T>& cmp, unsigned) {
ar & cmp.invert_;
}
} }
int main() {
using MyMap = std::map<int, std::string, StateFullCmp<int> >;
std::stringstream ss;
{
MyMap const m {
{ { 1, "one" }, { 2, "two" }, { 3, "three" } },
StateFullCmp<int> { true } // inverted order
};
std::cout << "====== original ordern";
for (auto& e : m)
std::cout << e.first << " -> " << e.second << "n";
boost::archive::text_oarchive oa(ss);
auto cmp_copy = m.key_comp();
oa << cmp_copy << m;
}
{
boost::archive::text_iarchive ia(ss);
MyMap::key_compare cmp_state { false }; // default initialization
ia >> cmp_state;
MyMap deserialized(cmp_state);
ia >> deserialized;
std::cout << "====== deserialized ordern";
for (auto& e : deserialized)
std::cout << e.first << " -> " << e.second << "n";
}
}
现在打印:
====== original order
3 -> three
2 -> two
1 -> one
====== deserialized order
3 -> three
2 -> two
1 -> one
相关文章:
- 定义具有非标准签名的自定义映射比较器
- 如何为映射和priority_queue编写比较器,其中元素是二维数组
- 使用更大的比较器初始化映射
- STL映射比较器能否以某种方式获取指向映射本身的指针?
- 使用自定义比较器C++映射,不插入所有元素
- C++ priority_queue使用带有 lambda 比较器错误的映射
- C++:对象键的多映射自定义比较器
- C++函数来返回基于参数的比较器通用映射类型?
- c++中一对对象的映射比较器
- 映射的 Lambda 键比较器
- STL 映射自定义比较器
- 将带有自定义比较器的映射传递到功能
- 带有自定义比较器的映射不起作用
- 是否有映射的查找()以使用带参数的比较器
- 成员功能作为映射比较器
- 标准::映射与λ比较器
- 映射运算符<条件 - 无效的比较器
- 使用自己的比较器运算符()进行映射<>。在找不到 KEY 的情况下给出错误
- c++比较器函数,为映射指定特定的键顺序
- 具有透明比较器和异构意义上的非唯一元素的映射或集合