Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::copy_if: stably copying elements that satisfy a predicate

std::copy_if tests every element, copies only those with a true predicate result, and returns the end of the written destination portion.

Version: C++23

Syntax

template<class InputIterator, class OutputIterator, class Predicate>
constexpr OutputIterator copy_if(InputIterator first, InputIterator last,
                                 OutputIterator result, Predicate pred);

std::copy_if(first, last, result, pred) from <algorithm> evaluates pred(*i) for each of the N elements in [first, last) and copies those for which the result is true. Their relative order is preserved. If M values are written, it returns the iterator advanced M positions from result; operator + is not required.

The predicate is invoked exactly N times. It must not modify the source element or invalidate iterators. The destination needs room for the worst case, the whole input range, unless an insertion iterator is used; the algorithm does not resize an ordinary container itself.

The source [first, last) and the sequence of the first N potential destination positions beginning at result must not overlap, even when the predicate selects fewer elements. A predicate or assignment exception under any standard execution policy, including seq, calls std::terminate. An empty range returns result.

Examples

#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <vector>

int main() {
    const std::vector<int> source{1, 4, 2, 5};
    std::array<int, 4> destination{};
    const auto end = std::copy_if(source.begin(), source.end(), destination.begin(),
                                  [](int value) { return value % 2 == 0; });
    const auto written = std::distance(destination.begin(), end);
    std::cout << written;
    for (auto it = destination.begin(); it != end; ++it) std::cout << ' ' << *it;
    std::cout << '\n';
}

Result

2 4 2

std::copy_if → 2 4 2

Sources