STL标准库容器函数对象简单实用

知识点:

1、标准库函数对象:标准库定义了一组表示算术运算符、关系运算符和逻辑运算符的类,每个类分别定义了一个执行命名操作的调用运算符。这些类都被定义成模版的形式,我们可以为指定具体的应用类型

2、函数适配器:bind1st、bind2nd 把二元函数转为一元函数,以便算法调用

3、标准库部分算法函数 count_if、find_if、transform 的使用

示例代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <string>

using namespace std;

int main()
{
    //find greater than 4
    vector<int> ivec{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int number = count_if( ivec.begin(), ivec.end(), bind2nd( greater<int>(), 4 ) );
    cout << "greater 5 number:" << number << endl;
    //less than 4
    int number2 = count_if( ivec.begin(), ivec.end(), bind1st( greater<int>(), 4 ) );
    cout << "greater 5 number:" << number2 << endl;

    //find string not biu
    vector<string> svec{ "biu", "lalala", "biu", "biu", "biu" };
    auto iter = find_if( svec.begin(), svec.end(), bind2nd( not_equal_to<string>(), "biu" ) );
    cout << "not equal biu string is:" << *iter << endl;

    //all number multiple 2
    vector<int> ivec2( 10, 2 );

    for( auto i : ivec2 )
    {
        cout << i << " ";
    }

    cout << endl;
    transform( ivec2.begin(), ivec2.end(), ivec2.begin(), bind2nd( multiplies<int>(), 2 ) );

    for( auto i : ivec2 )
    {
        cout << i << " ";
    }

    cout << endl;
    system( "pause" );
    return 0;
}

执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值