C++謂詞

it_xiangqiang發表於2020-11-10

4.2 謂詞

4.2.1 謂詞概念

概念:

  • 返回bool型別的仿函式稱為謂詞
  • 如果operator()接受一個引數,那麼叫做一元謂詞
  • 如果operator()接受兩個引數,那麼叫做二元謂詞

4.2.2 一元謂詞

示例:

#include <vector>
#include <algorithm>

//1.一元謂詞
struct GreaterFive{
	bool operator()(int val) {
		return val > 5;
	}
};

void test01() {

	vector<int> v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}

	vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());
	if (it == v.end()) {
		cout << "沒找到!" << endl;
	}
	else {
		cout << "找到:" << *it << endl;
	}

}

int main() {

	test01();

	system("pause");

	return 0;
}

總結:引數只有一個的謂詞,稱為一元謂詞

4.2.3 二元謂詞

示例:

#include <vector>
#include <algorithm>
//二元謂詞
class MyCompare
{
public:
	bool operator()(int num1, int num2)
	{
		return num1 > num2;
	}
};

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;

	//使用函式物件改變演算法策略,排序從大到小
	sort(v.begin(), v.end(), MyCompare());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}

int main() {

	test01();

	system("pause");

	return 0;
}

總結:引數只有兩個的謂詞,稱為二元謂詞

相關文章