3、设计泛型算法 --函数调用 实现filter

对于一整数vector,我们必须返回新的vector, 采取小于或大于等不同条件下返回不同的vector。

 

#include <iostream>
#include <vector>

#include <algorithm>

using namespace std;

typedef bool (*func_type)(int, int);


bool less_than(int a, int b)
{
    return a < b ? true : false;
}

bool more_than(int a, int b)
{
    return a > b ? true : false;
}

//vector<int> filter(vector<int> vec, int value, bool (*pred)(int, int))
vector<int> filter(vector<int> vec, int value, func_type pred)
{
    vector<int> nvec;

    for (size_t i = 0; i < vec.size(); ++i)
    {   
        if (pred(vec[i], value))
        {   
            nvec.push_back(vec[i]);
        }   
    }   
    return nvec;
}

void print_ivec(vector<int> ivec, const string str)
{
    cout << str << ": ";
    vector<int>::const_iterator it = ivec.begin();
    for (; it != ivec.end(); ++it)
    {   
        cout << *it << ' ';
    }   
    cout << endl;
}


int main(int argc, const char *argv[])
{
    vector<int> ivec;
    
    for (int i = 0; i < 20; ++i)
    {   
        ivec.push_back(i);
    }   
    print_ivec(ivec, "init_ivec");
    
    vector<int> nvec;
    nvec = filter(ivec, 10, less_than);
    print_ivec(nvec, "less_than");
    
    nvec = filter(ivec, 10, more_than);
    print_ivec(nvec, "more_than");

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值