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

equal_to - C++ Reference (cplusplus.com)

STL中equal_to仿函数的使用问题

posted on   OctoberKey  阅读(764)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示