Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::copy handle overlapping ranges?

Tags:

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?

like image 762
Adrian McCarthy Avatar asked Dec 23 '09 13:12

Adrian McCarthy


2 Answers

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).

like image 113
John Feminella Avatar answered Sep 20 '22 09:09

John Feminella


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]
like image 39
Alon Avatar answered Sep 21 '22 09:09

Alon