STL学习(1)——std::equal_to
说明
std::equal_to
作用
用于比较两个对象或两个值,它能像函数一样被调用,因此可以把它当作参数进行传递。运算符“==”是无法像参数一样被传递的。
用法
可以直接对c++原生类型进行比较,也可以对自定义类型进行比较,自定义类型需要重载“==”运算符。
示例
// equal_to example
#include <iostream> // std::cout
#include <utility> // std::pair
#include <functional> // std::equal_to
#include <algorithm> // std::mismatch
struct RGB
{
int R;
int G;
int B;
constexpr bool operator==(const RGB& rgb) const
{
return rgb.R == R && rgb.G == G && rgb.B == B;
}
constexpr bool operator==(int rgb) const
{
return ((rgb >> 16) & 0xff) == R &&
((rgb >> 8) & 0xff) == G &&
((rgb >> 0) & 0xff) == B;
}
};
constexpr bool operator==(RGB& lhs, int rhs)
{
return ((rhs >> 16) & 0xff) == lhs.R &&
((rhs >> 8) & 0xff) == lhs.G &&
((rhs >> 0) & 0xff) == lhs.B;
}
int main() {
std::pair<int*, int*> ptiter;
int foo[] = { 10,20,30,40,50 };
int bar[] = { 10,20,40,80,160 };
// 当参数传递
ptiter = std::mismatch(foo, foo + 5, bar, std::equal_to<int>());
std::cout << "First mismatching pair is: " << *ptiter.first;
std::cout << " and " << *ptiter.second << '\n';
RGB red = { 255, 0, 0 };
RGB red1 = { 255, 0, 0 };
RGB blue = { 0, 0, 255 };
// 直接调用
bool equal = std::equal_to<RGB>()(red, blue);
std::cout << "red equals to blue: " << equal << std::endl;
equal = std::equal_to<RGB>()(red, red1);
std::cout << "red equals to red1: " << equal << std::endl;
// 比较不同的类型
equal = std::equal_to<>()(1, 1.0);
std::cout << "1 equals to 1.0: " << equal << std::endl;
equal = std::equal_to<>()(red, 0xff0000);
std::cout << "red equals to 0xff0000: " << equal << std::endl;
return 0;
}
参考
std::equal_to in C++ with Examples - GeeksforGeeks
posted on 2022-08-03 16:53 OctoberKey 阅读(764) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通