billion.bin来源是福布斯网页2017年
实验要求:
1、读取2进制文件billion.bin,形成一个vector<billion>的容器内容。
2、使用for_each遍历vector容器内所有元素,调用find_billion(“China”, 60,70 ),打印出满足要求的所有富翁。
3、上述find_billion是一个函数对象。
实验内容:
billion.bin是struct billion的2进制存储,billion的定义为:
struct billion {
int no;
char name[20];
char account[6];
int age;
char company[20];
char country[20];
};
实验代码:
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <memory.h>
using namespace std;
struct billion
{
int no;
char name[20];
char account[6];
int age;
char company[20];
char country[20];
};
ostream& operator<<(ostream& os,billion &b) //输出流
{
os << "编号" << '\t' << "姓名" << "\t\t" << "国家" << "\t\t" << "公司" << '\t' << "年龄" << '\t' << "资产" << endl;
os << b.no << '\t' << b.name << '\t' << b.country << '\t' << b.company << '\t' << b.age << '\t' << b.account << endl;
return os;
}
class find_billion
{
private:
billion b;
char* country;
int min;
int max;
public:
find_billion()
{
memset(this->country,NULL,sizeof(this->country));
min = 0;
max = 0;
}
find_billion(char *country,int min,int max)
{
this->country = country;
this->min = min;
this->max = max;
}
void operator()(billion b)
{
if(b.age > min && b.age < max && !strcmp(b.country,country)) //相同则返回0,大于返回1,小于返回负数
{
cout << b << endl;
}
}
};
int main()
{
ifstream in;
in.open("d:\\billion.bin");
vector<billion>v;
billion b;
in.read((char *)&b,sizeof(billion));
while(!in.eof())
{
in.read((char *)&b,sizeof(billion));
v.push_back(b);
}
// vector<billion>::iterator it = v.begin(); //用于输出vector里面的内容
// for(;it != v.end();it++)
// {
// cout << *it << endl;
// }
find_billion bil = for_each(v.begin(),v.end(),find_billion("China",60,70));
in.close();
return 0;
}