Algorithm Copy If Function

C++ Algorithm copy_if function is used to copy the elements of the container [first,last] into a different container starting from result for which the value of pred is true.

Syntax

Example

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

Parameter

first : It is an input iterator to the first element of the range, where the element itself is included in the range.

last : It is an input iterator to the last element of the range, where the element itself is not included in the range.

result : It is an output iterator to the first element of the new container in which the elements are copied.

pred : It is a Unary function that accepts one element as argument and checks for the condition specified.

Return value

An iterator to the last element of the new range beginning with the result is returned.

Example 1

Example

#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:

Output

b contains: 20 10 4

Example 2

Example

#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:

Output

The new vector using copy_if contains:7 9 0 0 0 0

Complexity

The complexity of the function is linear starting from the first element to the last one.

Data races

Some or all of the container objects are accessed.

Exceptions

The function throws an exception if any of the container elements throws one.

Input Required

This code uses input(). Please provide values below: