The Wayback Machine - https://web.archive.org/web/20240702184217/https://www.geeksforgeeks.org/stdreplace-stdreplace_if-c/
Open In App

std::replace and std::replace_if in C++

Last Updated : 26 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

std::replace

Assigns new_value to all the elements in the range [first, last) that compare to old_value. The function use operator == to compare the individual elements to old_value 

Function Template : 

void replace (ForwardIterator first, 
              ForwardIterator last,
              const T& old_value,
              const T& new_value)
first, last : 
Forward iterators to the initial and final positions
in a sequence of elements.
old_value : Value to be replaced.
new_value : Replacement value.

Return Value : 
This function do not return any value. If elements that needs to be replace is found then element 
replaced otherwise remain unchanged. 

Examples: 

Input : 10 20 30 30 20 10 10 20 
Output : 10 99 30 30 99 10 10 99 
// Replaced value 20 in vector to 99.

Input : 3 5 7 8 9 5 4 
Output : 3 5 7 12 9 5 4  
// Replaced value 8 by 12.

CPP




// CPP program to find and replace the value
// with another value in array
// using std::replace
#include <bits/stdc++.h>
using namespace std;
 
// Driver code
int main()
{
    int arr[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // variable containing the old and new values
    int old_val = 20, new_val = 99;
 
    // print old array
    cout << "Original Array:";
    for (int i = 0; i < n; i++)
        cout << ' ' << arr[i];
    cout << '\n';
 
    // Function used to replace the values
    replace(arr, arr + n, old_val, new_val);
 
    // new array after using std::replace
    cout << "New Array:";
    for (int i = 0; i < n; i++)
        cout << ' ' << arr[i];
    cout << '\n';
 
    return 0;
}


Output

Original Array: 10 20 30 30 20 10 10 20
New Array: 10 99 30 30 99 10 10 99

std::replace_if

Assigns new_value to all the elements in range [first, last) for which pred returns true. 
Function Template :  

void replace_if (ForwardIterator first, ForwardIterator last,
                   UnaryPredicate pred, const T& new_value)
first, last : Forward iterators to the initial and final positions
in a sequence of elelments.
pred : Unary function that accepts an element in the range as argument, and
returns a value convertible to bool.The returned value indicate whether
the element is to be replaced (if true, it is replaced).
The function shall not modify its argument.
old_value : Value to be replaced.
new_value : Replacement value. 

Examples: 

Input : 1 2 3 4 5 6 7 8 9 10  
Output : 0 2 0 4 0 6 0 8 0 10  
// Replaced all odd values to 0.

Input : 10 20 30 30 20 10 10 20 
Output : 10 4 30 30 4 10 10 4  
// Replaced all number divisible by 4 to 4.

CPP




// CPP code to find all the elements that are odd
// and replace them with 0.
// using std::replace_if
#include <bits/stdc++.h>
using namespace std;
 
// Function that is used in std::replace_if
// If number is odd return 1, else 0
// 1 (True) means replace the number
// 0 (False) means does not replace
bool IsOdd(int i)
{
  return ((i % 2) == 1);
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // print old array
    cout << "Original Array:";
    for (int i = 0; i < n; i++)
        cout << ' ' << arr[i];
    cout << '\n';
 
    // replacement value
    int new_val = 0;
 
    // replace_if function
    replace_if(arr, arr + n, IsOdd, new_val);
 
    // new array after using std::replace
    cout << "New Array:";
    for (int i = 0; i < n; i++)
        cout << ' ' << arr[i];
    cout << '\n';
 
    return 0;
}


Output

Original Array: 1 2 3 4 5 6 7 8 9 10
New Array: 0 2 0 4 0 6 0 8 0 10

Also you can add any kind of function in std::replace_if that can only have one argument only.

 



Similar Reads

std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header &lt;iostream&gt;. Use of precision : In the default floati
3 min read
std::oct , std::dec and std::hex in C++
This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in oc
2 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File &lt;string&gt; String Functionalities The
6 min read
std::stod, std::stof, std::stold in C++
std::stod() : It convert string into double. Syntax: double stod( const std::string&amp; str, std::size_t* pos = 0 ); double stod( const std::wstring&amp; str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This param
3 min read
std::setbase, std::setw , std::setfill in C++
The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : std::setbase (int base);decimal : if base is 10hexadecimal : if base is 16octal
3 min read
std::string::replace() in C++
The string replace() function in C++ replaces each element in the part of the string in the range [first, last). It is defined inside the std::string class in C++ as a member function to provide replace functionality. Syntax of String replace() The syntax of std::string::replace() is as follows: string&amp; replace( first, last, str);Parameters of
3 min read
std::istream_iterator and std::ostream_iterator in C++ STL
The STL is a very powerful library in C++. It is strongly built on the principles of template programming. The STL library has three main components : Containers: These classes define the data structures which are used to contain the data. The data may be stored in linked lists, or trees or arrays. The containers provided in the STL are vector, deq
6 min read
Difference between std::swap and std::vector::swap
The std::swap is a general function used to exchange the given values whereas the std::vector::swap is a specialized function that can swap all the contents of two different vector containers.Below are some major key differences between std::swap and std::vector::swap, std::swapstd::vector::swapThe std::swap() is a built-in function in C++ STL whic
3 min read
std::bitset::to_ullong and std::bitset::to_ulong in C++ STL
Bitset: A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than that of bool bs[N] and vector bs(N). However, a limitation of bitset is, N must be known at compile time, i.e., a constant (this limitation is no
2 min read
Difference between std::quick_exit and std::abort
std::quick_exit() It Causes normal program termination to occur without completely cleaning the resources. Syntax : void quick_exit(int exit_code) no except; In case of execution of threads the codes becomes complex and knowing the execution of threads is hard. While one the thread might be waiting for a process to end while the other thread is wai
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg