STL预定义函数适配器

bind1st(op, value)

bind2nd(op, value)

not1(op)

not2(op)

mem_fun_ref(op)

mem_fun(op)

ptr_fun(op)

// STL_算法操作.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

template<typename T>
struct IsOdd
{
	IsOdd(T n)
	{
		divisor = n;
	}
	bool operator()(T elementNum)
	{
		return !(elementNum%divisor);
	}
private:
	T divisor;
};

int main()
{
	vector<int> ivec;
	ivec.push_back(4);
	for (size_t i = 0; i<9 ;++i)
	{
		ivec.push_back(i);
	}
	ivec.push_back(4);

	for (std::vector<int>::iterator iter = ivec.begin(); iter!=ivec.end(); iter++ )
	{
		cout << *iter << " ";
	}

	int i = count(ivec.begin(), ivec.end(), 4);
	cout << endl << "一共有" << i << "个4" << endl;

	IsOdd<int> isodd(2);
	i = count_if(ivec.begin(), ivec.end(), isodd);
	cout << "一共有" << i << "个奇数" << endl;

	// bind2nd为函数适配器
	i = count_if(ivec.begin(), ivec.end(), not1(bind2nd(greater<int>(), 4)));	// param1 > param2
	// cout << "一共有" << i << "个大于4" << endl;
	cout << "一共有" << i << "个小于等于4" << endl;
	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/lasuerte/article/details/79066102