Copying Algorithms

Unique Copy with Predicate

Can I use std::ranges::unique_copy() with a predicate that depends on multiple object properties?

Abstract art representing computer programming

Yes, you can use std::ranges::unique_copy() with a predicate that depends on multiple object properties by providing a custom comparison function.

This allows you to define what it means for two objects to be "unique" based on your specific criteria.

Here’s an example using a custom comparison function with a Player class, where two Player objects are considered the same if they have the same Name and Level:

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

class Player {
  Player() = default;
  Player(std::string name, int level)
    : name(name), level(level) {}

  std::string getName() const { return name; }
  int getLevel() const { return level; }

  std::string name;
  int level;

bool customCompare(const Player& a, const Player& b) {
  return a.getName() == b.getName()
    && a.getLevel() == b.getLevel();

int main() {
  std::vector<Player> Source{
    {"Anna", 10}, {"Anna", 10},
    {"Bob", 20}, {"Bob", 25},
    {"Anna", 10}, {"Anna", 20}
  std::vector<Player> Dest;

  auto [in, out] = std::ranges::unique_copy(
    Source.begin(), Source.end(),
    Dest.begin(), customCompare

  for (auto it = Dest.begin(); it != out; ++it) {
    std::cout << it->getName() << " (Level "
      << it->getLevel() << ")\n";
Anna (Level 10)
Bob (Level 20)
Bob (Level 25)
Anna (Level 10)
Anna (Level 20)

In this example:

  • The Player class has Name and Level properties.
  • The customCompare() function returns true if both Name and Level are equal.
  • std::ranges::unique_copy() uses this custom comparison to determine uniqueness.

You can modify the customCompare() function to include more properties or different logic based on your requirements.

Steps to Use Custom Comparison:

  1. Define the Custom Comparison Function: Create a function that takes two objects and returns true if they should be considered equal.
  2. Call the std::ranges::unique_copy() algorithm: Pass the custom comparison function as the third argument to std::ranges::unique_copy().

This allows for flexible and powerful control over what constitutes a unique object, enabling complex comparisons based on multiple properties.

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