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

来源:互联网 发布:spring软件安卓版 编辑:程序博客网 时间:2024/04/29 12:02
我们在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;
}
原创粉丝点击