When copying data from one range to another, you have to be careful if there's partial overlap between the source and destination ranges. If the beginning of the destination range overlaps the tail of the source range, a plain sequential copy will garble the data. The C run-time library has memmove
in addition to memcpy
to handle such overlap problems.
I assume std::copy
works like memcpy
, in that it doesn't pay any regard to overlap between the source and destination regions. If you try to shift objects "down" in a std::vector
with std::copy
, you'll corrupt the data. Is there an STL algorithm analogue of memmove
to handle situations like this? Or should I roll my own with reverse iterators?
It doesn't handle overlapping ranges iff the beginning of the output range overlaps with the input range.
Fortunately, you can use std::copy_backward
instead (which requires that you don't overlap the end of the output range with the input range).
Preconditions for std::copy
, prohibits an overlap:
Prototype
template <class InputIterator, class OutputIterator> OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result);
Preconditions
[first, last)
is a valid range.- result is not an iterator within the range
[first, last)
.- There is enough space to hold all of the elements being copied. More formally, the requirement is that
[result, result + (last - first))
is a valid range. [1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With