Using Custom Comparison in replace()

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

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.

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().

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Replace without modifying original
How do I handle cases where std::ranges::replace() should not modify the original container but create a modified copy instead?
Real-world uses for replace_if()
What are some practical use cases for std::ranges::replace_if() in real-world applications?
Prevent buffer overflow in replace_copy()
How do I ensure that std::ranges::replace_copy() does not cause buffer overflows in the destination container?
Transform containers with replace_copy_if()
Can std::ranges::replace_copy_if() be used to transform data from one container type to another (e.g., std::vector to std::list)?
Use replace() with non-random access iterators
Is it possible to use std::ranges::replace() with containers that do not support random access iterators?
Using replace() in multi-threaded environment
Can I use std::ranges::replace() in a multi-threaded environment, and what precautions should I take?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant