简体   繁体   English

如何转储我的类(带有 stl 容器),以便下次快速加载?

[英]How to dump my class(with stl container) out, make it fast to load next time?

I have a large container class to read file and save some data, it looks like:我有一个大容器类来读取文件并保存一些数据,它看起来像:

class MyData {
 public:
  void Load(const std::vector<string>& file_paths) {  // this is a slow funuction, need to read a lot of files.
     for (const auto & f : file_paths) {
       // read file, and save the data in to stl containers
     }
  }
 private:
  std::vector<double> a;
  std::unordered_map<string, double>b; // there may be more containers.
}

everytime when i need to use this class, i need to:每次当我需要使用这个类时,我需要:

MyData mdata;
std::vector<std::string> fs; // thousands of files need to read
mdata.Load(fs); // very slow

but the Mdata not update frequently, Can i dump it out, and use the dumped class, so make it faster?但是 Mdata 不经常更新,我可以将它转储出来,并使用转储的类,这样让它更快吗? For example:例如:

MyData load_dump(const std::string& dump_file_path) {
  // help needed
}

const MyData& mdata = load_dump("dump.bin"); // load the dumped file, to speed up

Can you help on this?你能帮忙吗?

Sure you can.你当然可以。 For vector<double> you can simply use ofstream::write(a.data(), a.size()) .对于vector<double>你可以简单地使用ofstream::write(a.data(), a.size()) For things like maps you need to do some kind of serialization because their internal representation is more complex.对于地图之类的东西,您需要进行某种序列化,因为它们的内部表示更加复杂。 You could use http://www.boost.org/libs/serialization/ for a somewhat generic solution or you could write the code yourself.您可以使用http://www.boost.org/libs/serialization/作为某种通用的解决方案,或者您可以自己编写代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM