Alrott SlimRG Asked:2022-01-02 23:05:55 +0000 UTC2022-01-02 23:05:55 +0000 UTC 2022-01-02 23:05:55 +0000 UTC 将 std::unordered_map 保存/读取到文件的最快方法是什么 772 实际上,问题就在标题中: How to save/read std::unordered_map to file as faster as possible 值和键 --> 字符串。 PS地图中的条目不超过1000个 c++ 1 个回答 Voted Best Answer Harry 2022-01-03T00:13:22Z2022-01-03T00:13:22Z “傻瓜保护”——文件已打开、存在、录音是否通过等所有检查——我没写,自己加。最主要的是以二进制模式打开文件。 #include <string> #include <iostream> #include <fstream> #include <unordered_map> using namespace std; ostream& outStr(ostream& out, const string& s) { size_t l = s.size(); out.write((char*)&l,sizeof(l)); out.write(s.c_str(),l); return out; } istream& inStr(istream& in, string& s) { size_t l; in.read((char*)&l,sizeof(l)); s = string(l,' '); in.read(s.data(),l); return in; } void map2file(const unordered_map<string,string>& m, ostream& out_file) { size_t l = m.size(); out_file.write((char*)&l,sizeof(l)); for(auto& p: m) { outStr(out_file,p.first); outStr(out_file,p.second); } } void file2map(istream& in_file, unordered_map<string,string>& m) { size_t l; in_file.read((char*)&l,sizeof(l)); for(int i = 0; i < l; ++i) { string key; inStr(in_file,key); inStr(in_file,m[key]); } } int main(int argc, char * argv[]) { unordered_map<string,string> m = { {"aaa", "111" }, {"bbb", "222" }, {"ccc", "333" }, {"ddd", "444" }, {"eee", "555" } }, p; { ofstream out("data",ios::binary); map2file(m,out); } { ifstream in("data",ios::binary); file2map(in,p); for(auto& s: p) cout << s.first << " " << s.second << endl; } }
“傻瓜保护”——文件已打开、存在、录音是否通过等所有检查——我没写,自己加。最主要的是以二进制模式打开文件。