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.
Answers to questions are automatically generated and may not have been reviewed.
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()
.