一、题目要求
1、读取billion.bin二进制文件。内部存储内容
struct billion
{
int no;
char name[20];
char account[6];
int age;
char company[20];
char country[20];
};
2、撰写代码
1、将记录追加入vector<Billion>中
2、使用for_each遍历
3、撰写find_billion("China", 38, 45)函数对象
注:China是国家,38和45分别是年龄下限和上限
二、简单的代码实现
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <functional>
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,const Billion &b)
{
os << b.no << " " << b.name << " " << b.account << " " << b.age << " " << b.company << " " << b.country << endl;
return os;
}
struct find_billion
{
char country[20];
int start;
int send;
find_billion(const char country[], int start, int send)
{
strcpy(this->country, country);
this->start = start;
this->send = send;
}
void operator()(const Billion &b)
{
if(!strcmp(b.country, this->country))
{
if((b.age > this->start) && (b.age < this->send))
{
cout << b << endl;
}
}
}
};
int main(void)
{
ifstream in;
in.open("C:\\Users\\Lenovo\\Desktop\\billion.bin", ios_base::in|ios::binary);
vector<Billion> b;
Billion a;
in.read((char *)&a, sizeof(Billion));
while(!in.eof())
{
in.read((char *)&a, sizeof(Billion));
b.push_back(a);
}
for_each(b.begin(), b.end(), find_billion("China",38, 45));
in.close();
return 0;
}
1、简单总结
在C++中,若想要用到的函数对象参数大于两个时,首先考虑把该函数对象内传的参数作为结构体或类的成员变量,然后重载()即可,重载函数的参数就是for_each内容器的函数类型
注:C++读二进制文件的方法重点了解