我尝试编写代码以将 sparse_hash_map 的类型序列化为文件,但不知何故它不起作用,令人信服地告诉我这个错误消息:
/usr/local/include/sparsehash/sparsetable:1763:13: error: no matching function for call to object of type 'CharPointerToIntSerializer'
if ( !serializer(fp, &*it) ) return false; ^~~~~~~~~~
似乎 mymap.serialize 方法工作得很好,这是 mymap2.unsiialize 方法失败了,关于下面这段代码中的问题有什么想法吗?
#include <iostream>
#include <sparsehash/sparse_hash_map>
using google::sparse_hash_map; // namespace where class lives by default
using namespace std;
#define SIZE 13
struct CharPointerToIntSerializer {
bool operator()(FILE* fp, std::pair<char *, int>* value) const {
if (fread(value->first, SIZE, 1, fp) != 1) {
return false;
}
if (fread(&(value->second), sizeof(value->second), 1, fp) != 1)
return false;
return true;
}
// bool operator()(FILE* fp, const std::pair<const char *, int>& value) const {
bool operator()(FILE* fp, const std::pair<char *, int>& value) const {
for(int i = 0; i < SIZE; i++){
if (fwrite(value.first + i, 1, 1, fp) != 1)
return false;
}
if (fwrite(&value.second, sizeof(value.second), 1, fp) != 1)
return false;
return true;
}
};
int main(){
sparse_hash_map<char*, int> old_map,new_map;
char *p1, *p2;
p1 = (char *) malloc(10);
p2 = (char *) malloc(10);
strcpy(p1, "hello");
strcpy(p2, "world");
old_map[p1] = 1;
old_map[p2] = 2;
FILE* fp = fopen("hashtable.txt", "w");
old_map.serialize(CharPointerToIntSerializer(), fp);
cout << old_map[p1] << endl;
fclose(fp);
FILE* fp_in = fopen("hashtable.txt", "r");
new_map.unserialize(CharPointerToIntSerializer(), fp_in);
fclose(fp_in);
assert(old_map == new_map);
cout << new_map[p2] << endl;
}