• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    function template
    <algorithm>

    std::ranges::copy_backward

    namespace std::ranges {
      template <bidirectional_iterator I1,
                sentinel_for<I1> S1,
                bidirectional_iterator I2>
        requires indirectly_copyable<I1, I2>
      constexpr copy_backward_result<I1, I2>
        copy_backward(I1 first, S1 last, I2 result); // (1) C++20
    
      template <bidirectional_range R,
                bidirectional_iterator I>
        requires indirectly_copyable<iterator_t<R>, I>
      constexpr copy_backward_result<borrowed_iterator_t<R>, I>
        copy_backward(R&& r, I result);              // (2) C++20
    }
    

    概要

    指定された範囲の要素を後ろからコピーする。

    事前条件

    result(first,last] の範囲に含まれてはならない。

    効果

    [first,last) 内にある要素を、それぞれ [result - (last-first),result) へコピーする。

    コピーは last - 1 から順番に行い、1 以上 last - first 以下であるそれぞれの n について、*(result - n) = *(last - n) を行う。

    戻り値

    copy_backward_result {
      .in  = last,
      .out = result - (last - first),
    }
    

    計算量

    正確に last - first 回代入が行われる。

    備考

    last[result - (last-first), result) の範囲内にあるときには、copy() の代わりに copy_backward() を使うべきである。

    #include <algorithm>
    #include <iostream>
    #include <list>
    
    int main() {
      std::list<int> ls = { 1,2,3,4,5 };
      // 1,2,3 の範囲を、3,4,5 の値のある範囲へコピーする
      std::ranges::copy_backward(ls.begin(), std::next(ls.begin(), 3), ls.end());
    
      // 以下のコードだと期待した結果にならないことを確認しよう
      // std::ranges::copy(ls.begin(), std::next(ls.begin(), 3), std::next(ls.begin(), 2));
    
      std::ranges::copy(ls.begin(), ls.end(), std::ostream_iterator<int>(std::cout, ","));
    }
    

    出力

    1,2,1,2,3,
    

    バージョン

    言語

    • C++20

    処理系

    参照