STL-函数对象中的谓词

返回bool类型的仿函数叫谓词

  1. operator()接受一个参数,一元谓词
  2. operator()接受两个参数,二元谓词

一元

#include
#include
#include
using namespace std;

class First {
public:
	bool operator()(int num1)
	{
		return num1>5;
	}
};

void test01()
{
	vector<int> v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	
	vector<int>::iterator pos = find_if(v.begin(), v.end(), First());
	if (pos == v.end())
	{
		cout << "没找到!" << endl;
	}
	else {
		cout << "找到:" << *pos << endl;
	}
}


int main()
{
	test01();
	return 0;
}

二元

#include
#include
#include
using namespace std;

class Mycompare {
public:
	bool operator()(int num1,int num2)
	{
		return num1>num2;
	}
};

void test01()
{
	vector<int> v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	
	sort(v.begin(), v.end());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << endl;
	}
	cout << endl;
	cout << "------------------------" << endl;

	sort(v.begin(), v.end(),Mycompare());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << endl;
	}
	cout << endl;
	cout << "------------------------" << endl;
}


int main()
{
	test01();
	return 0;
}

你可能感兴趣的:(C,c++,算法,开发语言)