• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

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

    履歴 編集

    function template
    <algorithm>

    std::ranges::copy_if

    namespace std::ranges {
      template <input_iterator I,
                sentinel_for<I> S,
                weakly_incrementable O,
                class Proj = identity,
                indirect_unary_predicate<projected<I, Proj>> Pred>
        requires indirectly_copyable<I, O>
      constexpr copy_if_result<I, O>
        copy_if(I first, S last, O result, Pred pred, Proj proj = {}); // (1) C++20
    
      template <input_range R,
                weakly_incrementable O,
                class Proj = identity,
                indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred>
        requires indirectly_copyable<iterator_t<R>, O>
      constexpr copy_if_result<borrowed_iterator_t<R>, O>
        copy_if(R&& r, O result, Pred pred, Proj proj = {});           // (2) C++20
    }
    

    概要

    条件を満たす要素のみをコピーする。

    事前条件

    [first,last) の範囲と、[result,result + (last - first)) の範囲は重なっていてはならない。

    効果

    [first,last) 内のイテレータ i について pred(*i)true である要素を result へ順番にコピーする。

    戻り値

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

    計算量

    正確に last - first述語を適用する。

    備考

    このコピーは安定なコピーである。つまり、コピーによって要素の前後が入れ替わることは無い。

    #include <algorithm>
    #include <iostream>
    #include <vector>
    #include <iterator>
    
    bool isOdd(int x) { return x % 2 != 0; }
    
    int main() {
      std::vector<int> v1 = { 3, 1, 4 };
      std::vector<int> v2 = { 1, 5, 9 };
      std::vector<int> v3 = { 2, 6, 5 };
      std::vector<int> result(v1.size() + v2.size() + v3.size());
    
      // copy_if の戻り値を使って、複数のコンテナにある奇数を全て繋げる
      auto out = result.begin();
      out = std::ranges::copy_if(v1, out, isOdd).out;
      out = std::ranges::copy_if(v2, out, isOdd).out;
      out = std::ranges::copy_if(v3, out, isOdd).out;
    
      std::ranges::copy(result.begin(), out, std::ostream_iterator<int>(std::cout, ","));
    }
    

    出力

    3,1,1,5,9,5,
    

    バージョン

    言語

    • C++20

    処理系

    参照