Replacement Algorithms

Using Custom Comparison in replace()

Can I use std::ranges::replace() with custom comparison operators instead of ==?

Abstract art representing computer programming

std::ranges::replace() relies on the == operator to determine if an element should be replaced.

To use a custom comparison, you'll need to write a custom predicate and use std::ranges::replace_if(), which accepts a predicate function. Here's an example:

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

struct Player {
  std::string Name;
  int Score;
};

bool custom_compare(const Player &p) {
  return p.Name == "Anna";
}

int main() {
  std::vector<Player> Players = {
    {"Anna", 10},
    {"Bob", 20},
    {"Anna", 30},
    {"Carol", 40}
  };

  std::ranges::replace_if(
    Players, custom_compare, Player{"Unknown", 0}
  );

  for (const auto &p : Players) {
    std::cout << p.Name << ": " << p.Score << "\n";
  }
}
Unknown: 0
Bob: 20
Unknown: 0
Carol: 40

In this example, we replace all Player objects where the Name is "Anna" with a default Player object using std::ranges::replace_if(). The custom_compare() function determines which elements to replace.

If your comparison logic is more complex, you can encapsulate it in a lambda function. This approach provides flexibility and maintains readability.

Using custom comparisons allows you to tailor the behavior of replace_if() to fit your specific needs, making it a powerful tool for more advanced scenarios.

This Question is from the Lesson:

Replacement Algorithms

An overview of the key C++ standard library algorithms for replacing objects in our containers. We cover replace(), replace_if(), replace_copy(), and replace_copy_if().

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

This Question is from the Lesson:

Replacement Algorithms

An overview of the key C++ standard library algorithms for replacing objects in our containers. We cover replace(), replace_if(), replace_copy(), and replace_copy_if().

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:

  • 124 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