谓词的介绍与基本使用

谓词

概念

1.返回类型为bool的仿函数
2.接受一个参数—一元谓词
接受一个参数—二元谓词

1.一元谓词

⛽使用方法

因为返回值为bool类型,所以经常会将他使用成判断关系的函数
我们使用find_if()对谓词进行讲解,我们先要知道find_if()的代码

Pred—仿函数

template <class _InIt, class _Pr>
_NODISCARD _CONSTEXPR20 _InIt find_if(_InIt _First, const _InIt _Last, _Pr _Pred) { // find first satisfying _Pred
    _Adl_verify_range(_First, _Last);
    auto _UFirst      = _Get_unwrapped(_First);
    const auto _ULast = _Get_unwrapped(_Last);
    for (; _UFirst != _ULast; ++_UFirst) {
        if (_Pred(*_UFirst))//对这个指针进行解引用然后传入仿函数进行判断真假
        //所以只传进去了一个值,而判断关系需要两个值,那么另一个只就是自己给定的了
         {
            break;
        }
    }

    _Seek_wrapped(_First, _UFirst);
    return _First;
}
#include
using namespace std;
#include
class Com
{
public:
	bool operator()(int v)//我们这里为什么只传过来了一个数字呢???
	{
		return v > 2;
	}
};
void test()
{
	vector<int>v;
	for (int i = 0; i < 10; i++) v.push_back(i);

	//Com()---匿名对象
	vector<int>::iterator  it=find_if(v.begin(), v.end(), Com());//使用仿函数实现
	if (it != v.end()) cout << "find  " <<*it<< endl;
	else cout << "not find" << endl;

	vector<int>::iterator its = find_if(v.begin(), v.end(), com);
	if (its != v.end()) cout << "find  " << *its << endl;
	else cout << "not find" << endl;

}
函数实现讲解:

1.从起始迭代器开始一直到终止迭代器结束,将每一个数字带入函数中,返回bool类型,只有真才会成为迭代器最终的值否则直到最后的迭代器才会停止,所以判断的条件是将it与v.end()进行比较
2.我们这里使用了两种实现的方式,第一种是使用仿函数的形式,传入的是匿名对象第二种使用的是普通函数的形式,传入的是函数名

2.二元谓词

在我们介绍二元谓词实现之前,需要先介绍一个函数sort函数(位于algorithm头文件中)

template <class _RanIt>
_CONSTEXPR20 void sort(const _RanIt _First, const _RanIt _Last) { // order [_First, _Last)
    _STD sort(_First, _Last, less<>{});//我们能看到这里是less,默认就是小到大排序
#include
using namespace std;
#include
#include
void print(vector<int> v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) cout << *it << " ";
	cout << endl;
}
class Com
{
public:
	bool operator()(int v1, int v2)
	{
		return v1 > v2;
	}
};
bool com(int v1, int v2)
{
	return v1 > v2;
}
void test()
{
	vector<int> v;
	v.push_back(2);
	v.push_back(12);
	v.push_back(41);
	v.push_back(25);
	v.push_back(45);
	v.push_back(24);
	print(v);

	sort(v.begin(), v.end());//默认是小到大排序
	print(v);

	sort(v.begin(), v.end(), Com());//仿函数
	print(v);

	cout << "--------------------" << endl;

	sort(v.begin(), v.end());//默认是小到大排序
	print(v);

	sort(v.begin(), v.end(), com);
	print(v);
}

谓词的介绍与基本使用_第1张图片

函数实现讲解:

我们的sort进行排序,排序就是比较,自然需要两个参数,所以传参就是两个,返回依旧是bool类型

总结:对于谓次我们需要紧紧把握住,因为后面都是他,离不开他了已经。

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