C++ std::equal_to实例讲解
C++ std::equal_to实例讲解
时间:2022-04-07
本文章向大家介绍C++ std::equal_to实例讲解,主要分析其语法、参数、返回值和注意事项,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。
std::equal_to允许将相等比较用作函数,这意味着可以将其作为参数传递给模板和函数。对于相等运算符==,这是不可能的,因为运算符不能作为参数传递。
头文件:
#include <functional.h>
模板类别:
template struct equal_to:binary_function { // Declaration of the equal operation bool operator() (const T& x, const T& y) const { return x==y; } // Type of first parameter typedef T first_argument_type; // Type of second parameter typedef T second_argument_type; // The result is returned // as bool type typedef bool result_type; }
用法:
std::equal_to <int> ()
参数:该函数接受参数T的类型作为参数,以供函数调用进行比较。
返回类型:它根据条件返回布尔值(让a和b为2个元素):
- 真正:如果a等于b。
- 假:如果a不等于b。
下面是C++中std::equal_to的图示:
程序1:
// C++ code to illustrate std::equal_to
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
using namespace std;
// Driver Code
int main()
{
// Intialise vectors
vector<int> v1 = { 50, 55, 60,
65, 70 };
vector<int> v2 = { 50, 55, 85,
65, 70 };
// Declaring pointer of pairs
pair<vector<int>::iterator,
vector<int>::iterator>
pairs1;
// Use mismatch() function to
// search first mismatch between
// v1 and v2
pairs1 = mismatch(v1.begin(), v1.end(),
v2.begin(),
equal_to<int>());
// Print the mismatch pair
cout << "The 1st mismatch element"
<< " of 1st container:";
cout << *pairs1.first << endl;
cout << "The 1st mismatch element"
<< " of 2nd container:";
cout << *pairs1.second << endl;
return 0;
}
输出:
The 1st mismatch element of 1st container:60 The 1st mismatch element of 2nd container:85
程序2:
// C++ program to illustrate std::equals_to
#include <algorithm>
#include <functional>
#include <iostream>
using namespace std;
// Template
template <typename A, typename B,
typename U = std::equal_to<int> >
// Function to check if a = b or not
bool f(A a, B b, U u = U())
{
return u(a, b);
}
// Driver Code
int main()
{
int X = 1, Y = 2;
// If X is equals to Y or not
cout << std::boolalpha;
cout << f(X, Y) << '\n';
X = -1, Y = -1;
// If X is equals to Y or not
cout << f(X, Y) << '\n';
return 0;
}
输出:
false true
参考: http://www.cplusplus.com/reference/functional/equal_to/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了