巧用标准c++中的算法函数,对数组进行操作

我们在c/c++中常用的指针也是算子,它符合算子的所有特性,所以我们可以用c++标准模板库中的algorithm算法函数,来对数组进行操作。这种操作,对于简化程序是十分有帮助的,下面我简单使用程序演示一下如何使用他们,希望能够给网友提供一种思路和一些启发。
#include <iostream>
#include <algorithm>
#include <functional>

using namespace std;

template <typename T>
struct SVisit: public unary_function<T, void>
{
    inline void operator()( const T& t ) const
    {
        cout << t << endl;
    }
};

template <typename T>
struct SEqualer: public binary_function<T, T, bool>
{
    inline bool operator()( const T& t, const T& value ) const
    {
        return t == value;
    }
};

int main( void )
{
    int arr[] = { 2, 5, 6, 9, 1, 0, 4, 6 };
    int len   = sizeof( arr ) / sizeof( int );

    cout << "arr's size = " << len << endl;
    for_each( arr, arr + len, SVisit<int>() );

    cout << "Replace 6 by 10" << endl;
    typedef SEqualer<int>    SIntReplacer;
    replace_if( arr, arr + len, binder2nd<SIntReplacer>( SIntReplacer(), 6 ), 10 );
    for_each( arr, arr + len, SVisit<int>() );

    cout << "Delete value = 10" << endl;
    typedef SEqualer<int>    SIntDeleter;
    len = remove_if( arr, arr + len, binder2nd<SIntDeleter>( SIntDeleter(), 10 ) ) - arr;
    for_each( arr, arr + len, SVisit<int>() );

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值