Copying Algorithms

Copying Between Different Container Types

How do I copy elements from a container to a different type of container, like from a std::vector to a std::list?

Abstract art representing computer programming

Copying elements from one type of container to another, such as from a std::vector to a std::list, is straightforward with std::ranges::copy().

The ranges library does not restrict the types of containers, as long as they support iterators.

Here’s an example that demonstrates how to copy elements from a std::vector to a std::list:

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

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

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

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

In this example, the std::vector Source contains the elements we want to copy, and the std::list Destination is the target container.

The std::ranges::copy() function copies elements from Source to Destination.

If the destination container does not initially have enough space, you can resize it or use an inserting iterator like std::back_inserter:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <list>
#include <vector>

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

  std::ranges::copy(
    Source, std::back_inserter(Destination));  

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

In this case, std::back_inserter is used to insert elements at the end of the Destination list, ensuring it grows as needed to accommodate all elements from the Source.

Using std::ranges::copy() with different container types is flexible and efficient, allowing you to work with various data structures seamlessly.

Just ensure that the destination container can grow dynamically if it doesn't have pre-allocated space.

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

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