The source code and dockerfile for the GSW2024 AI Lab.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

64 lines
1.9 KiB

4 weeks ago
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <fstream>
  4. #include <sparsepp/spp.h>
  5. using spp::sparse_hash_map;
  6. using namespace std;
  7. struct StringToIntSerializer
  8. {
  9. bool operator()(std::ofstream* stream, const std::pair<const std::string, int>& value) const
  10. {
  11. size_t sizeSecond = sizeof(value.second);
  12. size_t sizeFirst = value.first.size();
  13. stream->write((char*)&sizeFirst, sizeof(sizeFirst));
  14. stream->write(value.first.c_str(), sizeFirst);
  15. stream->write((char*)&value.second, sizeSecond);
  16. return true;
  17. }
  18. bool operator()(std::ifstream* istream, std::pair<const std::string, int>* value) const
  19. {
  20. // Read key
  21. size_t size = 0;
  22. istream->read((char*)&size, sizeof(size));
  23. char * first = new char[size];
  24. istream->read(first, size);
  25. new (const_cast<string *>(&value->first)) string(first, size);
  26. // Read value
  27. istream->read((char *)&value->second, sizeof(value->second));
  28. return true;
  29. }
  30. };
  31. int main(int , char* [])
  32. {
  33. sparse_hash_map<string, int> users;
  34. users["John"] = 12345;
  35. users["Bob"] = 553;
  36. users["Alice"] = 82200;
  37. // Write users to file "data.dat"
  38. // ------------------------------
  39. std::ofstream* stream = new std::ofstream("data.dat",
  40. std::ios::out | std::ios::trunc | std::ios::binary);
  41. users.serialize(StringToIntSerializer(), stream);
  42. stream->close();
  43. delete stream;
  44. // Read from file "data.dat" into users2
  45. // -------------------------------------
  46. sparse_hash_map<string, int> users2;
  47. std::ifstream* istream = new std::ifstream("data.dat");
  48. users2.unserialize(StringToIntSerializer(), istream);
  49. istream->close();
  50. delete istream;
  51. for (sparse_hash_map<string, int>::iterator it = users2.begin(); it != users2.end(); ++it)
  52. printf("users2: %s -> %d\n", it->first.c_str(), it->second);
  53. }