谓词
C++ 刚入门的时候,学过这些东西,不过好久不用都忘得差不多了。昨天突然见到有点懵逼。记录一下,防止下次懵逼。
在C++中,谓词是指一种可以被用于判断某个条件的函数或者函数对象。谓词常常用于泛型算法的参数中,比如STL中的算法。
- 函数接受一个参数,称为一元谓词
- 函数接受两个参数,称为二元谓词
示例代码
/*
* @Author: lify
* @Date: 2023-12-08 09:08:46
* @LastEditors: lify
* @LastEditTime: 2023-12-08 09:31:22
* @FilePath: /TEXT/Predicate/main.cpp
* @Description:
* @custom_info:
* @custom_copyright: Copyright (c) 2023 by lify, All Rights Reserved.
*/
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
// ************************************* 一元谓词 *************************************
bool Unaryfunc1(int a)
{
if(a > 10)
{
return true;
}
return false;
}
struct UnaryFunc2
{
bool operator()(int a)
{
if (a > 10)
{
return true;
}
return false;
}
};
std::function<bool(int)> Unaryfunc3 = [](int a)->bool
{
if(a > 10)
{
return true;
}
return false;
};
// ************************************* 二元谓词 *************************************
bool Binaryfunc1(int a, int b)
{
if(a + b > 10)
{
return true;
}
return false;
}
struct BinaryFunc2
{
bool operator()(int a, int b)
{
if (a + b > 10)
{
return true;
}
return false;
}
};
std::function<bool(int, int)> Binaryfunc3 = [](int a, int b)->bool
{
if (a + b > 10)
{
return true;
}
return false;
};
int main(int argc, char const *argv[])
{
std::vector<int> list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 21, 31, 41};
std::vector<int>::iterator iterator_1 = std::find_if(list.begin(), list.end(), Unaryfunc1);
std::vector<int>::iterator iterator_2 = std::find_if(list.begin(), list.end(), UnaryFunc2());
std::vector<int>::iterator iterator_3 = std::find_if(list.begin(), list.end(), Unaryfunc3);
std::cout << "一元谓词:" << *iterator_1 << " " << *iterator_2 << " " << *iterator_3 << std::endl;
std::vector<int>::iterator iterator_4 = std::find_if(list.begin(), list.end(), std::bind(Binaryfunc1, std::placeholders::_1, 4));
std::vector<int>::iterator iterator_5 = std::find_if(list.begin(), list.end(), std::bind(Binaryfunc1, std::placeholders::_1, 5));
std::vector<int>::iterator iterator_6 = std::find_if(list.begin(), list.end(), std::bind(Binaryfunc1, std::placeholders::_1, 6));
std::cout << "二元谓词:" << *iterator_4 << " " << *iterator_5 << " " << *iterator_6 << std::endl;
return 0;
}