...

/

Understanding the Constrained Algorithms

Understanding the Constrained Algorithms

Using the std::copy_if algorithm

The standard library provides over 100 general-purpose algorithms. As we discussed in the introductory lesson for the ranges library earlier, these have one thing in common: they work with abstract ranges with the help of iterators. They take iterators as arguments, and they sometimes return iterators. That makes it cumbersome to repeatedly use with standard containers or arrays. Here’s an example:

Press + to interact
auto l_odd = [](int const n) {return n % 2 == 1; };
std::vector<int> v{ 1, 1, 2, 3, 5, 8, 13 };
std::vector<int> o;
auto e1 = std::copy_if(v.begin(), v.end(),
std::back_inserter(o),
l_odd);
int arr[] = { 1, 1, 2, 3, 5, 8, 13 };
auto e2 = std::copy_if(std::begin(arr), std::end(arr),
std::back_inserter(o),
l_odd);

In this snippet, we have a vector v and an array arr, and we copy the odd elements from each of these two to a second vector, o. For this, the std::copy_if algorithm is used. This takes begin and end input iterators (defining the input range), an output iterator to a second range, where the copied elements will be inserted, and a unary predicate (in this example, a lambda expression). What it returns is an iterator to the destination range past the last copied element. ...