replace_if() Function in C++

bookmark

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
void print(vector<int>& v)
{
    for(int i = 0; i < v.size(); i++)
        cout << v[i] << " ";
    cout << endl;
}
 
bool IsEven(int i)
{
    return ((i%2) == 0);
}
 
int main()
{
    vector<int> v = {1, 2, 3, 4 , 5, 6, 7, 8, 9, 10};
 
    cout << "v : ";
    print(v);
    // Replace even numbers with 1
    replace_if (v.begin(), v.end(), IsEven, 1);
    cout << "After replacing even elements with 1\n";
    cout << "v : ";
    print(v);
}

 

Output:
$ gcc test.cpp
$ a.out
v : 1 2 3 4 5 6 7 8 9 10 
After replacing even elements with 1
v : 1 1 3 1 5 1 7 1 9 1