Set Algorithms

Using Custom Comparators

How can I use includes() with a custom comparator?

Abstract art representing computer programming

To use std::ranges::includes() with a custom comparator, you need to define a comparator function that specifies the order of elements in your sets.

The comparator should be a callable object (like a lambda function) that takes two elements as parameters and returns true if the first element is considered less than the second.

Here’s a step-by-step guide:

  1. Define your sets and the comparator function: The sets can be any type of container that supports forward iterators, and the comparator function determines the order.
  2. Call std::ranges::includes() with the comparator: Pass the sets and the comparator to the function.

Here’s an example using sets of integers, where the comparator defines a descending order:

#include <algorithm>
#include <iostream>
#include <set>

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

  // Custom comparator for descending order
  auto Comparer = [](const int& A, const int& B) {
    return A > B;
  };

  if (std::ranges::includes(A, B, Comparer)) {
    std::cout << "A includes B";
  } else {
    std::cout << "A does not include B";
  }
}
A includes B

In this example, the Comparer() lambda function is passed to std::ranges::includes(). The function checks if all elements in B are present in A considering the custom order defined by the comparator.

Custom Comparators for Complex Types

For more complex types, like a custom class, you need to adjust the comparator accordingly. Here's an example using a Character class, comparing based on a Name attribute:

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

class Character {
 public:
  Character(std::string Name) : Name{Name} {}
  std::string Name;
};

int main() {
  std::vector<Character> A{
    {"Aragorn"}, {"Frodo"}, {"Gimli"}};
  std::vector<Character> B{
    {"Frodo"}, {"Gimli"}};

  // Comparator for ascending order by Name
  auto Comparer = [](
    const Character& A,
    const Character& B
  ) {
    return A.Name < B.Name;
  };

  if (std::ranges::includes(A, B, Comparer)) {
    std::cout << "A includes B";
  } else {
    std::cout << "A does not include B";
  }
}
A includes B

Here, the Comparer() lambda compares Character objects based on their Name attribute. The algorithm works similarly, ensuring all elements in B are in A according to the custom comparison.

Using custom comparators allows std::ranges::includes() to be flexible and work with various data types and ordering schemes.

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

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