函数对象一元函数实例

#include 
#include 
#include 

using namespace std;

/*
STL中的一元函数基类
template
struct unary_function
{
    typedef _A argument_type;
    typedef _R result_type;
};
*/
//应用STL模板一元函数必须从unary_function基类派生

template<class _In, class _Out>
class CSum : public unary_function<_In, _Out>
{
public:
    CSum()
    {
        m_sum = 0;
    }

    CSum(_Out sum)
    {
        m_sum = sum;
    }

    void operator()(_In n)
    {
        m_sum += n;
    }

    _Out GetSum()const
    {
        return m_sum;
    }

private:
    _Out m_sum;
};

int main()
{
    vector<int> vi;
    for(int i = 1; i <= 100; i++)
    {
        vi.push_back(i);
    }
    CSum<int, int> cs = for_each(vi.begin(), vi.end(), CSum<int, int>());	//无参
    CSum<int, int> cs_1 = for_each(vi.begin(), vi.end(), CSum<int, int>(100));  //有参
    cout << cs.GetSum() << endl;
    cout << cs_1.GetSum() << endl;

    vector<float> vif;
    float f = 1.3f;
    for(int i = 1; i <= 100; i++)
    {
        vif.push_back(f);
        f += 1.0f;
    }
    CSum<float, float> cs0 = for_each(vi.begin(), vi.end(), CSum<float, float>());
    cout << cs0.GetSum() << endl;

    return 0;
}

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