【发布时间】:2018-05-30 13:20:33
【问题描述】:
我正在尝试使用 Boost 序列化一个包含向量和整数的 minHeap 对象。
struct minHeap {
std::vector<keyNode> heapStructure; // A vector of many keyNodes
int size; // Current size of vector
minHeap() {
size = 0;
}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned version)
{
ar & heapStructure;
ar & size;
}
};
现在heapStructure 是keyNode 的向量,每个keyNode 包含一个字符、整数和对象keyNode 本身的两个指针。
struct keyNode {
char data; // The character itself
int frequency; // Occurances of the character in the data stream.
keyNode * leftNode, *rightNode; // Left and right children of the root node (the keyNode itself)
keyNode() {
data = NULL;
frequency = 0;
leftNode = NULL;
rightNode = NULL;
}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned version)
{
ar &data;
ar &frequency;
ar &leftNode;
ar &rightNode;
}
};
下面的(示例)代码显示了我如何序列化和反序列化文件。
// Write Encoded Stream to File
ofstream outFile;
string outPath = filePath + ".enc";
outFile.open(outPath, ios::out | ios::binary); // TODO: Fix the output path
bitsetR bitStorage(outputStream);
boost::archive::binary_oarchive output(outFile);
output << bitStorage;
output << hTree;
outFile.close();
ifstream inFile;
inFile.open("demo.txt.enc"); // TODO: Fix the output path
bitsetR bitStr("");
boost::archive::binary_iarchive input(inFile);
minHeap temp;
input >> bitStr;
input >> temp;
序列化时我没有收到任何错误,但反序列化失败并出现以下错误(VS 2017):
Exception Thrown: Input Stream Error (boost::archive::archive_exception)
我应该在这里注意到bitsetR 对象成功反序列化。反序列化minHeap对象时抛出异常。
【问题讨论】:
-
什么是bitsetR?什么是输出流?
-
@sehe bitsetR 是 boost::dynamic_bitset (我在您的答案之一中使用了代码来序列化动态位集)。 outputStream 只是一个字符串,我用它来初始化 bitsetR 对象。
标签: c++ pointers serialization boost deserialization