How to Use std::copy in C++: Syntax and Examples
In C++, you use
std::copy from the <algorithm> header to copy elements from one range to another. It requires three iterators: the start and end of the source range, and the start of the destination range. The function copies elements in order until the source range is exhausted.Syntax
The std::copy function has this syntax:
InputIt first: Iterator to the start of the source range.InputIt last: Iterator to the end of the source range (one past the last element).OutputIt d_first: Iterator to the start of the destination range where elements will be copied.
The function copies elements from first up to but not including last into the destination starting at d_first.
cpp
template<class InputIt, class OutputIt> OutputIt copy(InputIt first, InputIt last, OutputIt d_first);
Example
This example copies elements from one vector to another using std::copy. It shows how to copy all elements from the source vector to the destination vector.
cpp
#include <iostream> #include <vector> #include <algorithm> // for std::copy int main() { std::vector<int> source = {10, 20, 30, 40, 50}; std::vector<int> destination(source.size()); // allocate space std::copy(source.begin(), source.end(), destination.begin()); std::cout << "Copied elements: "; for (int num : destination) { std::cout << num << ' '; } std::cout << '\n'; return 0; }
Output
Copied elements: 10 20 30 40 50
Common Pitfalls
Common mistakes when using std::copy include:
- Not allocating enough space in the destination container before copying, which causes undefined behavior.
- Using overlapping ranges, which
std::copydoes not handle safely (usestd::copy_backwardinstead). - Passing incorrect iterators that do not represent valid ranges.
cpp
#include <vector> #include <algorithm> #include <iostream> int main() { std::vector<int> src = {1, 2, 3}; std::vector<int> dest; // no space allocated // Wrong: destination has no space, this causes undefined behavior // std::copy(src.begin(), src.end(), dest.begin()); // Correct: allocate space first dest.resize(src.size()); std::copy(src.begin(), src.end(), dest.begin()); for (int n : dest) std::cout << n << ' '; std::cout << '\n'; return 0; }
Output
1 2 3
Quick Reference
Tips for using std::copy:
- Include
<algorithm>header. - Ensure destination has enough space before copying.
- Use iterators to specify source and destination ranges.
- For overlapping ranges, use
std::copy_backward.
Key Takeaways
Use std::copy with three iterators: source start, source end, and destination start.
Always allocate enough space in the destination container before copying.
std::copy does not handle overlapping ranges safely; use std::copy_backward for that.
Include to access std::copy.
Check iterator validity to avoid undefined behavior.