Using std::ranges::copy_n()
and a manual loop to copy n
elements from one range to another both achieve the same end goal, but there are some key differences to consider.
std::ranges::copy_n()
std::ranges::copy_n()
is more readable and expresses the intent clearly.Here’s how you use std::ranges::copy_n()
:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> Source{1, 2, 3, 4, 5};
std::vector<int> Destination(5);
std::ranges::copy_n(
Source.begin(), 3, Destination.begin());
for (int Value : Destination) {
std::cout << Value << ", ";
}
}
1, 2, 3, 0, 0,
Here’s an example of manually copying n
elements using a loop:
#include <iostream>
#include <vector>
int main() {
std::vector<int> Source{1, 2, 3, 4, 5};
std::vector<int> Destination(5);
for (size_t i = 0; i < 3; ++i) {
Destination[i] = Source[i];
}
for (int Value : Destination) {
std::cout << Value << ", ";
}
}
1, 2, 3, 0, 0,
std::ranges::copy_n()
is more concise and easier to understand at a glance.std::ranges::copy_n()
for clear and concise code when you just need to copy a specified number of elements.By understanding these differences, you can choose the appropriate method for your specific use case, balancing readability, flexibility, and performance.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the 7 copying algorithms in the C++ standard library: copy()
, copy_n()
, copy_if()
, copy_backward()
, reverse_copy()
, rotate_copy()
, and unique_copy()
.