×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

std::replace_if() function with example in C++ STL

C++ STL | std::replace_if() function: Here, we are going to learn about the replace_if() function of algorithm header in C++ STL with example.
Submitted by IncludeHelp, on May 25, 2019

C++ STL std::replace_if() function

replace_if() function is a library function of algorithm header, it is used to replace the value in a given range based on the given unary function that should accept an element in the range as an argument and returns the value which should be convertible to bool (like 0 or 1), it returns value indicates whether the given elements can be replaced or not?

Note: To use replace_if() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.

Syntax

Syntax of std::replace_if() function

std::replace_if(
    iterator start, 
    iterator end, 
    unary_function, 
    const T& new_value);

Parameter(s)

  • iterator start, iterator end – these are the iterators pointing to the starting and ending positions in the container, where we have to run the replace operation.
  • unary_function – is a unary function that will perform the condition check on all elements in the given range and the elements which pass the condition will be replaced.
  • new_value – a value to be assigned instead of an old_value.

Return value

void – it returns noting.

Sample Input and Output

//function to check EVEN value
bool isEVEN(int x)
{
    if (x % 2 == 0)
        return 1;
    else
        return 0;
}

Input:
vector<int> v{ 10, 20, 33, 23, 11, 40, 50 };
    
//replacing all EVEN elements with -1
replace_if(v.begin(), v.end(), isEVEN, -1);
    
Output:
-1 -1 33 23 11 -1 -1

C++ STL program to demonstrate use of std::replace_if() function

In this program, we have a vector and replacing all EVEN numbers with -1.

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

//function to check EVEN value
bool isEVEN(int x)
{
    if (x % 2 == 0)
        return 1;
    else
        return 0;
}

int main()
{
    //vector
    vector<int> v{ 10, 20, 33, 23, 11, 40, 50 };

    //printing vector elements
    cout << "before replacing, v: ";
    for (int x : v)
        cout << x << " ";
    cout << endl;

    //replacing all EVEN elements with -1
    replace_if(v.begin(), v.end(), isEVEN, -1);

    //printing vector elements
    cout << "after replacing, v: ";
    for (int x : v)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

before replacing, v: 10 20 33 23 11 40 50
after replacing, v: -1 -1 33 23 11 -1 -1

Reference: C++ std::replace_if()

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.