1.函数对象使用
#include <iostream>
using namespace std;//STL-函数对象(仿函数)class MyAdd
{
public:int operator()(int v1, int v2){return v1 + v2;}
};
//1、函数对象在使用时,可以像普通函数那用调用,可以有参数,可以有返回值
void test01()
{MyAdd myAdd;cout << myAdd(10, 10) << endl;
}// 2、函数对象超出普通函数的概念,函数对象可以有自己的状态
class MyPrint
{
public:MyPrint(){this->m_count = 0;}void operator()(string test){cout << test << endl;this->m_count++;}int m_count; // 内部自己状态
};void test02()
{MyPrint myPrint;myPrint("Hello World!");myPrint("Hello World!");myPrint("Hello World!");myPrint("Hello World!");cout << "MyPrint调用的次数: " << myPrint.m_count << endl;
}void doPrint(MyPrint& mp, string test)
{mp(test);
}// 3、函数对象可以作为参数传递
void test03()
{MyPrint myPrint;doPrint(myPrint, "Hello C++!");
}int main()
{test01();cout << "------------------------" << endl << endl;test02();cout << "------------------------" << endl << endl;test03();//**************************************system("pause");return 0;
}
2.谓词-一元谓词
#include <iostream>
using namespace std;//STL-一元谓词
#include<vector>
#include<algorithm>class GreaterFive
{
public:bool operator()(int val){return val > 5;}
};void test01()
{vector<int>v;for (int i = 0; i < 10; i++){v.push_back(i);}//查找容器中 有没有大于5的数字//GreaterFive() 匿名函数对象vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());if (it == v.end()){cout << "未找到!" << endl;}else{cout << "找到了大于5的数字为:" << *it << endl;}
}int main()
{test01();cout << "------------------------" << endl << endl;//test02();//cout << "------------------------" << endl << endl;//test03();//**************************************system("pause");return 0;
}
3.二元谓词
#include <iostream>
using namespace std;//STL-二元谓词#include<vector>
#include<algorithm>class MyCompare
{
public:bool operator()(int val1, int val2) //参数为两个 , 二元谓词{return val1 > val2; //降序}
};void test01()
{vector<int>v;v.push_back(10);v.push_back(40);v.push_back(20);v.push_back(30);v.push_back(50);sort(v.begin(), v.end());for (vector<int>::iterator it = v.begin(); it != v.end(); it++){cout << *it << " ";}cout << endl;cout << "------------------------" << endl << endl;//使用函数对象 改变算法策略,变为排序规则 从大到小sort(v.begin(), v.end(), MyCompare());for (vector<int>::iterator it = v.begin(); it != v.end(); it++){cout << *it << " ";}cout << endl;
}int main()
{test01();cout << "------------------------" << endl << endl;//test02();//cout << "------------------------" << endl << endl;//test03();//**************************************system("pause");return 0;
}