C++map容器里的所有内容以二进制方式保存与读取到文件
原地址 http://www.chinadmd.com/file/w6wscter3u6osooaapvco63u_2.html读写二进制文件。 Class 用法.将map存进二进制文件,高速读写。#include#include#include#includeusing namespace std;class STUDENT{publi
·
原地址 http://www.chinadmd.com/file/w6wscter3u6osooaapvco63u_2.html
读写二进制文件。
Class 用法.
将map存进二进制文件,高速读写。
#include <fstream>
#include <string>
#include <map>
#include <iostream>
using namespace std;
class STUDENT{
public:
string name;
int age;
};
int main()
{
map<int,STUDENT> obm, VM;
int num;
STUDENT stu;
num = 23;
stu.name = "张山";
stu.age = 55;
obm.insert(make_pair(num, stu));
num = 24;
stu.name = "王五";
stu.age = 55;
obm.insert(make_pair(num, stu));
num = 25;
stu.name = "什么";
stu.age = 55;
obm.insert(make_pair(num, stu));
num = 26;
stu.name = "哎呀";
stu.age = 55;
obm.insert(make_pair(num, stu));
//显示
cout << "学号\t姓名\t年龄" << endl;
map<int,STUDENT>::iterator iter = obm.begin();
while (iter != obm.end()){
cout << iter->first << "\t" << iter->second.name << "\t" << iter->second.age << endl; iter++; //保存
}
ofstream out("22.txt",ios::binary);
if (!out.is_open()) {
cout << "File is open fail!" << endl;
}
iter = obm.begin();
while (iter != obm.end()) {
out.write((char*)&iter->first,sizeof(int));
out.write((char*)&iter->second,sizeof(stu));
iter++;
}
out.close(); //读取
ifstream in("22.txt",ios::binary);
if (!in.is_open()) {
cout << "File is open fail!" << endl;
}
while (!in.eof()) {
in.read((char*)&num,sizeof(int));
in.read((char*)&stu,sizeof(stu));
VM.insert(make_pair(num,stu));
}
in.close(); //显示
iter = VM.begin();
while (iter != VM.end()) {
cout << iter->first << " " << iter->second.name << " " << iter->second.age << endl; iter++;
}
return 0;
}
更多推荐
已为社区贡献1条内容
所有评论(0)