std::copy_if list cpp code example

Example: what does copy_if c++

//C++ STL program to demonstrate use of
//std::copy_if() function
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    //declaring & initializing an int array
    int arr[] = { 10, 20, 30, -10, -20, 40, 50 };
    //vector declaration
    vector<int> v1(7);

    //copying 5 array elements to the vector
    copy_if(arr, arr + 7, v1.begin(), [](int i) { return (i >= 0); });

    //printing array
    cout << "arr: ";
    for (int x : arr)
        cout << x << " ";
    cout << endl;

    //printing vector
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    return 0;
}

Tags:

Cpp Example