Copying Algorithms

Copying from Multiple Source Ranges

How can I copy elements from multiple source ranges into a single destination container?

Abstract art representing computer programming

Copying elements from multiple source ranges into a single destination container can be done using multiple calls to std::ranges::copy() or similar algorithms.

The key is to keep track of the current position in the destination container to ensure elements are copied correctly.

Here’s an example where we copy elements from two source ranges into one destination container:

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

int main() {
  std::vector<int> Source1{1, 2, 3};
  std::vector<int> Source2{4, 5, 6};
  std::vector<int> Destination(6);

  auto it = std::ranges::copy(
    Source1, Destination.begin()).out; 

  std::ranges::copy(Source2, it); 

  for (int Value : Destination) {
    std::cout << Value << ", ";
  }
}
1, 2, 3, 4, 5, 6,

In this example:

  • We first copy elements from Source1 into Destination.
  • We then use the returned iterator it to start copying elements from Source2 immediately after the elements from Source1.

If you have more source ranges, you can continue this process:

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

int main() {
  std::vector<int> Source1{1, 2, 3};
  std::vector<int> Source2{4, 5, 6};
  std::vector<int> Source3{7, 8, 9};
  std::vector<int> Destination(9);

  auto it = std::ranges::copy(
    Source1, Destination.begin()).out; 

  it = std::ranges::copy(Source2, it).out; 
  std::ranges::copy(Source3, it); 

  for (int Value : Destination) {
    std::cout << Value << ", ";
  }
}
1, 2, 3, 4, 5, 6, 7, 8, 9,

This method ensures that all elements from the source ranges are copied into the destination container sequentially.

Make sure the destination container has enough space to hold all elements from all source ranges. If not, you should resize the destination container accordingly before copying.

Using this approach, you can efficiently combine elements from multiple source ranges into a single destination container.

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

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