Home »
C++ STL
std::replace() function with example in C++ STL
C++ STL | std::replace() function: Here, we are going to learn about the replace() function of algorithm header in C++ STL with example.
Submitted by IncludeHelp, on May 21, 2019
C++ STL std::replace() function
replace() function is a library function of algorithm header, it is used to replace an old value with a new value in the given range of a container, it accepts iterators pointing to the starting and ending positions, an old value to be replaced and a new value to be assigned.
Note: To use replace() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.
Syntax
Syntax of std::replace() function
std::replace(
iterator start,
iterator end,
const T& old_value,
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.
- old_value – is the value to be searched and replaced with the new value.
- new_value – a value to be assigned instead of an old_value.
Return value
void – it returns noting.
Sample Input and Output
Input:
vector<int> v{ 10, 20, 10, 20, 10, 30, 40, 50, 60, 70 };
//replacing 10 with 99
replace(v.begin(), v.end(), 10, 99);
Output:
99 20 99 20 99 30 40 50 60 70
C++ STL program to demonstrate use of std::replace() function
In this program, we have a vector and we are assigning a new value to an old value.
//C++ STL program to demonstrate use of
//std::replace() function
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
//vector
vector<int> v{ 10, 20, 10, 20, 10, 30, 40, 50, 60, 70 };
//printing vector elements
cout << "before replacing, v: ";
for (int x : v)
cout << x << " ";
cout << endl;
//replacing 10 with 99
replace(v.begin(), v.end(), 10, 99);
//printing vector elements
cout << "after replacing, v: ";
for (int x : v)
cout << x << " ";
cout << endl;
return 0;
}
Output
before replacing, v: 10 20 10 20 10 30 40 50 60 70
after replacing, v: 99 20 99 20 99 30 40 50 60 70
Reference: C++ std::replace()