Custom Comparison for std::equal()
How do I customize the comparison behavior for equal()
?
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.
Comparison Algorithms
An introduction to the eight main comparison algorithms in the C++ Standard Library