2

基本上,我有我的霍夫曼表

std::map<std::string, char> ciMap;

其中 string 是位模式,char 是所述模式表示的值。问题是如何将其存储为压缩文件的标题,以便在我想解码时可以再次构建相同的地图?

尝试将其存储为二进制:

size_t mapLen = ciMap.size();
outFile.write(reinterpret_cast<char*>(&mapLen), sizeof(size_t));
outFile.write(reinterpret_cast<char*>(&ciMap), sizeof(ciMap));

后来建立:

inFile.read(reinterpret_cast<char*>(&mapLen), sizeof(size_t));
inFile.read(reinterpret_cast<char*>(&ciMap), sizeof(mapLen));

不起作用,我得到字符串初始化错误......与NULL有关。有什么建议么?如果您有更好的方法来存储我想听的位和值。

4

3 回答 3

4

你可以自己做,也可以用 boost 来做:http: //www.boost.org/doc/libs/1_37_0/libs/serialization/doc/index.html。您当前尝试的只是将地图视为普通的旧数据类型,这本质上意味着它是 C 数据类型。但事实并非如此,因此它无法保存/加载。boost 序列化正确地做到了。看看它。如果您不想使用它,可以执行以下操作:

typedef std::map<std::string, char> my_map;
my_map ciMap;

// saving
std::ofstream stream("file.txt");
for(my_map::const_iterator it = ciMap.begin(); it != ciMap.end(); ++it) {
    stream << it->first << " " << it->second << std::endl;
}

// loading
char c;
std::string bits;
std::ifstream stream("file.txt");
while(stream >> bits >> c)
    ciMap.insert(std::make_pair(bits, c));

请注意,如果存储的字符也可以是空白字符,则上述内容需要进行一些更改。因此,最好在写出之前先转换为 int,然后在加载时读取为 int。实际上,我推荐 boost 序列化和 boost iostreams ( http://www.boost.org/doc/libs/1_37_0/libs/iostreams/doc/index.html ),其中包括一个压缩流,它也可以透明地压缩你的数据.

于 2008-12-09T01:43:39.917 回答
3

您不能以这种方式将二进制值序列化到磁盘。内存中的表示不仅仅是一个连续的内存块,即使它是它也可能包含相对于块地址的指针。

您需要遍历地图并单独序列化每个项目。然后将它们带回您通过从磁盘中逐一读取项目并将它们重新插入地图来重建地图。

于 2008-12-09T01:38:16.887 回答
2

好问题。这里的问题是默认容器不支持序列化 - 你必须自己编写它,这很痛苦,但它是可能的。

以下是如何将 a 序列化为std::map文本格式。您可以调整它以写入您需要的任何二进制格式。只需将<<运算符替换为readsand writes

template<typename K, typename V>
std::ostream &operator << (std::ostream &out, const std::map<K,V> &map) {
    out << "map " << map.size() << "\n";
    for (typename std::map<K,V>::const_iterator i = map.begin(); i != map.end(); ++i) {
        out << (*i).first << "\n" << (*i).second << "\n";
    }
    return out;
}

template<typename K, typename V>
std::istream &operator >> (std::istream &in, std::map<K,V> &map) {
    std::string mapkeyword;
    size_t num;
    in >> mapkeyword >> num;
    for (size_t i = 0; i < num; ++i) {
        K key; V value;
        in >> key >> value;
        map[key] = value;
    }
    return in;
}
于 2008-12-09T01:34:59.373 回答