函数对象练习——寻找亿万富豪

一、题目要求

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++读二进制文件的方法重点了解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Star星屹程序设计

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值