内建函数对象(20221128)

STL中内建的一些函数对象

分类:

1)算术仿函数

2)关系仿函数

3)逻辑仿函数

用法:

这些仿函数所产生的对象、用法和一般函数完全相同。

需要引入头文件: #include

1、算术仿函数

实现四则运算;

其中negate为一元运算,其余都是二元运算。

#include

void test01()

{

    //negate 一元仿函数,取反仿函数

    negate<int>n;

    cout << n(50) << endl;//输出-50

    //plus 二元仿函数 加法仿函数

    plus<int>p;

    cout<<p(10, 20)<<endl;//30  

}

内建函数对象(20221128)_第1张图片

2、关系仿函数

void test02()

{

    //greater 大于仿函数

    vectorV1;

    V1.push_back(10);

    V1.push_back(5);

    V1.push_back(30);

    V1.push_back(20);

    for (vector::iterator it = V1.begin(); it != V1.end(); it++)

    {

         cout << *it << " ";

    }

    cout << endl;

    cout << "排序后:" << endl;

    sort(V1.begin(), V1.end(),greater());//greater() 大于仿函数

    for (vector::iterator it = V1.begin(); it != V1.end(); it++)

    {

        cout << *it << " ";

    }

}

3、逻辑仿函数

函数原型:

//函数原型

template<class T>bool logical_and<T> //逻辑与

template<class T>bool logical_or //逻辑或

template<class T>bool logical_not //逻辑非

void test03()

{

    vectorV1;

    V1.push_back(false);

    V1.push_back(true);

    V1.push_back(true);

    for (vector::iterator it = V1.begin(); it != V1.end(); it++)

    {

        cout << *it << " ";  //0 1 1

    }

    cout << endl;

    //利用逻辑非将容器V1搬运到容器V2中,并执行取反操作

    vectorV2;

    V2.resize(V1.size());//搬运前必须先resize()空间 ,与原容器大小相同

    transform(V1.begin(), V1.end(), V2.begin(), logical_not());//transform()搬运操作

    for (vector::iterator it = V2.begin(); it != V2.end(); it++)

    {

        cout << *it << " "; //1 1 0

    }

}

内建函数对象(20221128)_第2张图片

 

 

你可能感兴趣的:(c++学习,c++,算法)