Comparison Algorithms

Custom Comparison in C++

How do I customize the comparison behavior for equal()?

Abstract art representing computer programming

You can customize the comparison behavior for std::ranges::equal() by providing a custom comparison function as an additional argument.

This function should take two arguments (the elements to be compared) and return true if they should be considered equal. Here's a simple example:

#include <algorithm>
#include <vector>
#include <iostream>
#include <cmath> // Needed for std::abs

int main() {
  std::vector<int> A{1, -2, 3};
  std::vector<int> B{-1, 2, -3};

  auto absEqual = [](int x, int y) {
    return std::abs(x) == std::abs(y);
  };

  if (std::ranges::equal(A, B, absEqual)) {
    std::cout << "Ranges are equal";
  } else {
    std::cout << "Ranges are not equal";
  }
}
Ranges are equal

In this example, the custom comparison function absEqual() compares the absolute values of the elements from the two ranges. As a result, std::ranges::equal() returns true because the absolute values match.

You can use custom comparison functions to implement more complex logic. For instance, you can compare objects by specific attributes:

#include <algorithm>
#include <iostream>
#include <vector>

class Person {
 public:
  Person(std::string name, int age)
    : name{name}, age{age} {}
  std::string getName() const { return name; }
  int getAge() const { return age; }

 private:
  std::string name;
  int age;
};

int main() {
  std::vector<Person> A{{"Alice", 30}, {"Bob", 25}};
  std::vector<Person> B{{"Alice", 30}, {"Bob", 25}};

  auto nameEqual = [](
    const Person& p1, const Person& p2
  ) {
    return p1.getName() == p2.getName();
  };

  if (std::ranges::equal(A, B, nameEqual)) {
    std::cout << "Ranges are equal by name";
  } else {
    std::cout << "Ranges are not equal by name";
  }
}
Ranges are equal by name

In this example, the custom comparison function nameEqual() compares the name attribute of Person objects. Thus, std::ranges::equal() returns true if the names match, regardless of other attributes like age.

Custom comparison functions allow you to tailor the behavior of std::ranges::equal() to fit specific requirements, providing great flexibility in how you compare elements within collections.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved