Copying Algorithms

Copying between Custom Containers

Can I use std::ranges::copy() with custom containers that do not support iterators?

Abstract art representing computer programming

Using std::ranges::copy() with custom containers that do not support iterators is not directly possible because the ranges library relies on iterators to traverse the elements of the container.

However, you can make your custom container compatible with the ranges library by implementing the necessary iterator support.

To make your custom container work with std::ranges::copy(), you need to provide begin() and end() methods that return iterators.

Here’s an example of a simple custom container with iterator support:

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

// Custom container class
class CustomContainer {
 public:
  CustomContainer(std::initializer_list<int> list)
    : data(list) {}

  // Use vector's iterator types directly
  using iterator
    = std::vector<int>::iterator;
  using const_iterator
    = std::vector<int>::const_iterator;

  iterator begin() { return data.begin(); }
  iterator end() { return data.end(); }

  const_iterator begin() const {
    return data.begin(); }
  const_iterator end() const {
    return data.end(); }

 private:
  std::vector<int> data;
};

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

  std::ranges::copy(Source, Destination.begin());

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

In this example, we define a CustomContainer class that holds data in a std::vector<int>.

We also define an Iterator class and implement the necessary iterator operations (operator*, operator++, and operator!=). The begin() and end() methods return iterators to the start and end of the container.

By implementing iterator support in your custom container, you can use it with std::ranges::copy() and other ranges algorithms.

This approach allows you to leverage the power of the C++ ranges library with your own data structures.

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