#include<iostream>
#include<fstream>
#include<algorithm>
#include<iterator>
#include<functional>
#include<vector>
#include<string.h>
#include<numeric>
using namespace std;
// void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
// 第一个参数first 排序的数组的起始地址。
// 第二个参数last 结束的地址(最后一个数据的后一个数据的地址)
// 第三个参数comp是排序的方法:可以是从升序也可是降序 不写则默认的排序方法是从小到大排序
/* copy(a,a+n,arr)
前两个参数标示了被拷贝的范围 [a, a+n)最后那个参数表示了拷贝到的位置
也就是说要把 [a, a+n) 范围中的内容拷贝到 arr 所起始的位置上
*/
/* for_each函数
template<typename InputIterator, typename Function>
Function for_each(InputIterator beg, InputIterator end, Function f) {
while(beg != end)
f(*beg++);
}*/
/* eof()返回true时是读到文件的最后一个字符,其实不然,
C++ eof()函数返回true时是读到文件结束符0xFF,
而文件结束符是最后一个字符的下一个字符。
*/
/*
从billionaires中找到中国38~45岁 的亿万富翁!
要求:
1、读取2进制文件billion.bin,形成一个vector的容器内容。
2、使用for_each遍历vector容器内所有元素,调用find_billion(“China”, 38, 45),
打印出满足要求的所有富翁。
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];
};
思路:把文件内容调出来赋值给vector 写find_billion类 构造函数要赋三个值
再带入for_each遍历vector 重载operator()每次符合条件的输出
*/
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<<b.no <<" "<<b.name <<" "<<b.age<<" "<<b.account <<" "<<b.company <<endl;
return os;
}
class find_billion{
public:
char country[20];
int maxage;
int minage;
public:
find_billion(char* coun,int a,int b){
strcpy(country,coun);
maxage=a;
minage=b;
}
void operator()(billion bb){
if(bb.age>minage && bb.age<maxage && strcmp(bb.country,country)==0)
cout<<bb<<endl;
}
};
int main()
{
vector<billion> vv;
billion b;
ifstream iif("billion.bin");
while(!iif.eof()){
// ifstream& read(char* buffer,int len)
iif.read((char*)&b,sizeof(billion));
vv.push_back(b) ;
}
iif.close();
for_each(vv.begin() ,vv.end() ,find_billion("China",45,38));
return 0;
}