理解函数对象的函数适配器
// leran.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include<iostream>
#include <vector>
#include<algorithm>
#include<functional>
using namespace std;
class GT_cls
{
public:
GT_cls(size_t val = 0):bound(val){}
bool operator()(const string &s)
{
return s.size()>=bound;
}
private:
std::string::size_type bound;
};
int _tmain(int argc, _TCHAR* argv[])
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8};
vector<int> ivec(a, a+8);
size_t n1 = count_if(ivec.begin(), ivec.end(), bind2nd(less_equal<int>(), 5));
cout << "n1:" << n1 << endl;
//size_t n = count_if(ivec.begin(), ivec.end(), not1(bind2nd(less_equal<int>(), 5)));
size_t n2 = count_if(ivec.begin(), ivec.end(), bind1st(less_equal<int>(), 5));
cout << "n2:" << n2 << endl;
less_equal<int> le;
size_t n3 = le(5, 8);
cout << "n3:" << n3 << endl;
vector<int>::iterator ite = ivec.begin();
while((ite = find_if(ite, ivec.end(), bind2nd(greater<int>(), 5))) != ivec.end())
{
cout << *ite << " ";
ite++;
}
cout << endl;
sort(ivec.begin(), ivec.end(), greater<int>());
vector<int>::iterator ites = ivec.begin();
while(ites!= ivec.end())
{
cout << *ites << " ";
ites++;
}
}
输出结果:
n1:5
n2:4
n3:1
6 7 8
8 7 6 5 4 3 2 1