C++ Copy Algorithms: std::copy, copy_if, copy_n & move
이 글의 핵심
Range-based copy utilities: filtering, overlap, move for performance, and iterator pitfalls.
What are copy algorithms?
Copy algorithms move data from a source range to a destination: copy, copy_if, copy_n, move, remove_copy, and copy_backward for overlapping ranges.
Why use them? Less boilerplate than hand loops, clearer intent, and optimized library implementations.
Variants
- copy: full
[first, last) - copy_if: predicate selects elements
- copy_n: first
nfrom a start iterator - copy_backward: safe right shift in overlapping buffers
- move / move_backward: move semantics
copy vs copy_if vs copy_n
| Algorithm | Input | Selection | Destination size |
|---|---|---|---|
copy | [first, last) | all | last - first or grow via back_inserter |
copy_if | [first, last) | pred true | up to last - first |
copy_n | from first, count n | first n | at least n or back_inserter |
copy_n with fewer than n readable elements → UB — validate input length for streams.
copy_backward (overlapping ranges)
std::copy proceeds forward. If source and destination overlap and the block shifts right, unread source can be overwritten → UB. Use copy_backward(first, last, d_last) where d_last is the end of the destination range (reverse copy).
move_backward is the move analogue.
Iterator invalidation
Appending with back_inserter may reallocate vector and invalidate iterators. reserve reduces reallocations. Thread safety: shared containers need synchronization.
Performance vs memcpy
Trivially copyable types may compile to memmove-like code; non-trivial types (std::string, containers) require proper copy/move — never memcpy those.
Output iterators
back_inserter, front_inserter (lists/deques), inserter, ostream_iterator — choose by container and insertion policy.
Common pitfalls
- Destination too small — UB; use resize, reserve + back_inserter, or count.
- Overlap — use copy_backward / move_backward when shifting right.
- After std::move algorithm — sources are valid but unspecified; clear or reassign before reuse.
- copy vs move — large strings/vectors: move when source disposable.
FAQ
Q1: copy — full range copy.
Q2: copy_if — filter while copying.
Q3: move — cheap transfer for rvalue-like use.
Q4: remove_copy vs remove — copy-out filter vs mutating remove-erase idiom.
Q5: Overlap — copy_backward / temporary buffer.
Q6: Resources — Effective STL, C++ Primer, cppreference — copy.
One-line summary: Use STL copy algorithms for safe range copies; prefer move for large movable types when appropriate.
Related posts
- C++ Algorithm Replace
- C++ Algorithm Reverse
- C++ Algorithm Generate
- C++ Iterator guide
Keywords
std::copy, copy_if, copy_n, copy_backward, std::move, remove_copy, back_inserter, STL