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

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

using namespace std;

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

template
struct SEqualer: public binary_function
{
    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() );

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

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

    return 0;
}

你可能感兴趣的:(C/C++)