Replacement Algorithms

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?

Abstract art representing computer programming

To replace elements in a container without modifying the original, use std::ranges::replace_copy().

This function creates a new container with the modified elements, leaving the original unchanged. Here's an example:

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

int main() {
  std::vector<int> Source{1, 2, 3, 3, 3, 4, 5};
  std::vector<int> Destination(Source.size());

  std::ranges::replace_copy(
    Source, Destination.begin(), 3, 0);

  std::cout << "Original: ";
  for (const auto &num : Source) {
    std::cout << num << ", ";
  }
  std::cout << "\nModified: ";
  for (const auto &num : Destination) {
    std::cout << num << ", ";
  }
}
Original: 1, 2, 3, 3, 3, 4, 5, 
Modified: 1, 2, 0, 0, 0, 4, 5,

In this example, std::ranges::replace_copy() copies elements from Source to Destination. It replaces elements equal to 3 with 0 in the Destination container, but Source remains unchanged.

This approach is useful when you need to preserve the original data for further use or comparison. By creating a new container, you can apply transformations without risking unwanted side effects on the original dataset.

Always ensure that the destination container has sufficient size to accommodate the copied elements. You can resize the destination container beforehand, as shown in the example.

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:

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