Description:
This C++ article is about the copy_if() algorithm function with std::vector container.
It is an STL algorithm in <algorithm> header file. It copies by checking a condition.
copy_if() has one definition:
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred);
Return type : returns an integer, i.e the frequency of the element(val) which satisfies the predicate conditions.
Working: The copy_if( ) function takes 4 parameters, two iterators 'first' & 'last' , result , and pred.
Input iterators to the initial and final positions in a sequence. The range copied is [first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
Output iterator to the initial position of the range where the resulting sequence is stored. The range includes as many elements as [first,last)
. Unary function that accepts an element in the range as argument, and
returns a value convertible to bool
. The value returned indicates whether the element is to be copied
(if true
, it is copied). The function shall not modify any of its arguments.This can either be a
function pointer or a function object.
Implementation:
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
bool predicate(int n) {
return (n % 3 == 0);
}
int main(){
list<int> lis{1,2,3,4,5,6,7,8,9,10};
list<int> lis_size (lis.size());
// copy only multiple of three
auto it = std::copy_if (lis.begin(), lis.end(), lis_size.begin(), predicate);
lis_size.resize(std::distance(lis_size.begin(),it)); // shrink container to new size
std::cout << "Element contains:";
for (int& x: lis_size) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
Output:
Element contains: 3 6 9
Comments