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仿函数的使用问题

转载请注明出处:http://www.mrdmz.com/article/20230526/840847.html