Algorithm Copy If Function - C++ Programming Tutorial
C++ Course / STL Algorithm / Algorithm Copy If Function

Algorithm Copy If Function

BLUF: Mastering Algorithm Copy If Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Algorithm Copy If Function

C++ is renowned for its efficiency. Learn how Algorithm Copy If Function enables low-level control and high-performance computing in the tutorial below.

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

Example

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

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 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.

Input Required

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

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience