std::unique_copy 范围重叠

std::unique_copy with overlapping ranges

template< class InputIt, class OutputIt >
OutputIt unique_copy( InputIt first, InputIt last,
                      OutputIt d_first );

如果输入范围和输出范围重叠,使用std::unique_copy是否有效? 考虑以下两个示例案例

auto d_last = std::unique_copy(first, last, d_first);

  1. d_first <= first <= d_last <= last
  2. first <= d_first <= last <= d_last

std::unique_copy 的先决条件在 [algorithms#alg.unique-8]:

template<class InputIterator, class OutputIterator>
  constexpr OutputIterator
    unique_copy(InputIterator first, InputIterator last,
                OutputIterator result);

Preconditions:

  • The ranges [first, last) and [result, result+(last-first)) do not overlap.

所以这是未定义的行为。