std::copy() and std::copy_if() function in C++ copies the elements in the range, to another range. However std::copy_if() function copies the element based on result of unary function passed to it.
Syntax
Syntax of copy() and copy_if() function is
template <class InputIterator, class OutputIterator> OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result); template <class InputIterator, class OutputIterator, class UnaryPredicate> OutputIterator copy_if (InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred);
where
- first, last : Iterators to the initial and final positions in a sequence. Range copied is [first,last), which contains all the elements between first and last, including the element pointed by first.
- result : Iterator to the initial position of the range where the resulting sequence is stored. The range includes as many elements as [first,last).
- pred : It accepts an element in the range as argument, and returns a value convertible to bool. If returned value is true, it will be copied to
result
.
copy() copies the elements in the range [first,last) into the range beginning at result. copy_if() copies the elements in the range [first,last) for which pred returns true to the range beginning at result.
Behavior of copy_if() function is equivalent to:
OutputIterator copy_if (InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred) { while (first!=last) { if (pred(*first)) { *result = *first; ++result; } ++first; } return result; }
Example
The following code uses copy() and copy_if() to copy the contents of one vector to another and to display the resulting vector:
#include <iostream> // std::cout #include <algorithm> // std::copy #include <vector> // std::vector int main () { int myints[]={10,20,30,40,50,60,70}; std::vector<int> myvector (7); // Copy using copy() std::copy (myints, myints+7, myvector.begin()); for (std::vector<int>::iterator it = myvector.begin(); it!=myvector.end(); ++it){ std::cout << ' ' << *it; } // Output // 10 20 30 40 50 60 70 std::cout <<"\n"; std::vector<int> foo = {25,15,5,-5,-15}; std::vector<int> bar (foo.size()); // copy only positive numbers: auto it = std::copy_if(foo.begin(), foo.end(), bar.begin(), [](int i){return !(i<0);} ); // Shrink to output size bar.resize(std::distance(bar.begin(),it)); for (int& x: bar) { std::cout << ' ' << x; } // Output // 25 15 5 return 0; }