C++谓词,函数适配器

1 、谓词

谓词,就是一个判断式,是一个返回bool类型的函数,或者也可以是函数对象(仿函数)。
和函数对象(一元,二元)一样,谓词也有一元谓词和二元谓词之分,这个元一样的表示的是函数的参数有几个


#include <iostream>
using namespace std;

#include "string"
#include <vector>
#include <algorithm>
#include "functional"

class mygreat
{
public:
	mygreat(int init)
	{
		my_value = init;
	}
	bool operator() (int &value1)
	{
		if (my_value < value1)
		{
			return true;
		}
		else
			return false;
	}
private:
	int my_value;
};

int main(void)
{
	vector<int> v1;
	for (int i = 0; i < 20; i++)
	{
		v1.push_back(i + 1);
	}

	cout << "初始值:" << endl;
	for (vector<int>::iterator it1 = v1.begin(); it1 != v1.end(); it1++)
	{
		cout << *it1 << " ";
	}
	cout << endl;

	cout << "计算容器中等于3的个数" << endl;
	int num1 = count(v1.begin(), v1.end(), 3);
	cout << num1 << endl;

	cout << "计算容器中大于3的个数" << endl;
	int num2 = count_if(v1.begin(), v1.end(), mygreat(3));
	cout << num2 << endl;

	cout << "计算容器中大于n的个数" << endl;
	int gre_num;
	cout << "输入n的值:";
	cin >> gre_num;
	mygreat mygread_num3(gre_num);
	int num3 = count_if(v1.begin(), v1.end(), mygread_num3);
	cout << num3 << endl;

	system("pause");
}

2、函数适配器

有时候有这样的需求,我们的谓词是二元的,第一个参数来自容器内的元素,第二个参数来自我们自己设定个某个值(举个简单的例子帮助自己理解,比方我们要计算某个容器中大于100的值有多少个,这时候,显然我们要有两个参数,一个是容器内的每个参数都检查一遍,第二个参数是100这个值)
具体的我们来看STL中的一个函数count_if()(有if的通常要加谓词)

int main(void)
{
	//c++有预定好的great函数对象
	//下面简单用下下函数适配器

	cout << "预定义函数对象测试,计算容器中大于n的值" << endl;
	int n;
	cout << "输入n值:" << endl;
	cin >> n;
	//这里的bind2nd,是将后面的n作为greater<int>()的第二个参数(第一个参数来自容器,从v1.begin()到v1.end())
	int num4 = count_if(v1.begin(), v1.end(), bind2nd(greater<int>(),n));
	cout << num4 << endl;
	
	cout << "取反器使用,下面计算的是小于等于n的个数" << endl;
	int num5 = count_if(v1.begin(), v1.end(), not1(bind2nd(greater<int>(), n)));
	cout << num5 << endl;
	system("pause");
}
发布了46 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42718004/article/details/85857666