cb25a_c++_函数对象简介

cb25a_c++_函数对象简介
预定义的函数对象
https://blog.csdn.net/txwtech/article/details/104382505
negate<type>()
plus<type>()
minus<type>()
multilies<type>()
divides<type>()
modulus<type>()

equal_to<type>()
not_equal_to<type>()
less<type>()
greater<type>()
less_equal<type>()
greater_equal<type>()
logical_not<type>()
logical_and<type>()
logical_or<type>()

自定义的函数对象,智能型函数,比普通速度快。有自己的状态
cout << "用函数对象,printInt()自定义的" << endl;
for_each(ivec.begin(), ivec.end(), PrintInt());
容器和函数对象
算法和函数对象
for_each使用

/*cb25a_c++_函数对象简介
预定义的函数对象
https://blog.csdn.net/txwtech/article/details/104382505
negate<type>()
plus<type>()
minus<type>()
multilies<type>()
divides<type>()
modulus<type>()

equal_to<type>()
not_equal_to<type>()
less<type>()
greater<type>()
less_equal<type>()
greater_equal<type>()
logical_not<type>()
logical_and<type>()
logical_or<type>()

自定义的函数对象,智能型函数,比普通速度快。有自己的状态
cout << "用函数对象,printInt()自定义的" << endl;
    for_each(ivec.begin(), ivec.end(), PrintInt());
容器和函数对象
算法和函数对象
for_each使用
*/

#include <iostream>
#include <set>
#include <algorithm>
#include <vector>

using namespace std;

void print(int elem)
{
    cout << elem << ' ';
}
//函数对象,class必须要有operator()
class PrintInt
{
public:
    void operator()(int elem) const
    {
        cout << elem << ' ';
    }
};


int main()
{
    //set自动排序,红黑树,二叉树
    //set<int> aa;//省略后,默认的函数对象就是less<int>
    set<int, less<int>> b;//less<int>从小到大的顺序
    set<int, greater<int>> a;//从大到小
    a.insert(9);
    a.insert(3);
    a.insert(8);
    a.insert(1);
    a.insert(5);
    //for (set<int>::iterator iter = a.begin(); iter != a.end(); ++iter)
    for(set<int,greater<int>>::iterator iter=a.begin();iter!=a.end();++iter)
        cout << *iter << endl;
    
    vector<int> ivec;
    for (int i = 2; i <= 9; ++i)
    {
        ivec.push_back(i);
    }
    cout << "用for_each算法" << endl;
    //for_each(ivec.begin(), ivec.end, 函数或函数对象);
    for_each(ivec.begin(), ivec.end(), print);
    cout << "用函数对象,printInt()自定义的" << endl;
    for_each(ivec.begin(), ivec.end(), PrintInt());//函数对象,自动调用operator()函数
    return 0;
}
欢迎讨论,相互学习。 txwtech@163.com
原文地址:https://www.cnblogs.com/txwtech/p/12328141.html