The C++ Algorithm copy_if function is employed to duplicate the elements within the container [first, last] to another container starting from the result, where the predicate's value is true.
Syntax
template<class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if(InputIterator first, InputIterator last, OutputIterator result,UnaryPredicate pred);
Parameter
It serves as an input iterator pointing to the initial element within the range, encompassing the element itself within the specified range.
At the end: It serves as an input iterator pointing to the final element within the range, excluding the element itself from the range.
It serves as an output iterator pointing to the initial element of the fresh container where the elements get duplicated.
pred : A Unary function is designed to take a single element as input and verify the specified condition.
Return value
An iterator pointing to the final element of the fresh range starting from the outcome is provided.
Example 1
#include<iostream>
#include<algorithm>
#include<vector>
int main()
{
std::vector<int> a = {20,10, 4,-4,-10};
std::vector<int> b (a.size());
auto ti = std::copy_if(a.begin(),a.end(),b.begin(),[](int j){ return !(j<0);});
b.resize(std::distance(b.begin(),ti));
std::cout<<"b contains:";
for (int& x:b) std::cout<<" "<<x;
std::cout<<"\n";
return 0;
}
Output:
b contains: 20 10 4
Example 2
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
vector<int> u1={2,6,7,4,9,4};
vector<int> u2(6);
copy_if(u1.begin(), u1.end(), u2.begin(), [](int j){return j%2!=0;});
cout<<"The new vector using copy_if contains:";
for(int k=0; k<u2.size(); k++)
cout<<u2[k]<<" ";
}
Output:
The new vector using copy_if contains:7 9 0 0 0 0
Complexity
The function's complexity increases linearly as it iterates from the initial element to the final one.
Data races
Some or all of the container entities are retrieved.
Exceptions
The function will raise an exception if any of the container components also raises an exception.