Is there a way to serialize this type of hashmap<char *, int> in sparse_hash_map?

80 views
Skip to first unread message

Yin Steve

unread,
May 28, 2015, 9:47:50 AM5/28/15
to google-s...@googlegroups.com
In the previous post, I asked about some serialization problem about hashmap<std::string, int>. And now i'm wondering is there any wayy to serialize hashmap<char *, int> to file? Here is my code, and compiling it tells me this error message:

/usr/local/include/sparsehash/sparsetable:1763:13: error: no matching function for call to
      object of type 'CharPointerToIntSerializer'
      if ( !serializer(fp, &*it) )  return false;
            ^~~~~~~~~~
 
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/map.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

#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;
}

any kind of help will be appreciated here! :)
Reply all
Reply to author
Forward
0 new messages