Replace Element of an Array With Another in C++
To replace an element of an array, we can use the std::replace() that assigns new_value to all the elements in the range [first, last) that are equal to old_value. This function uses the operator == to compare the individual elements to the old_value.
Syntax of std::replace
void replace(first, last, old_value, new_value)
Here,
- 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.
C++ Program to Replace a Value in an Array
The below program demonstrates how we can replace a value in an array with another value.
C++
// C++ Program to find and replace the value #include <algorithm> #include <iostream> using namespace std; 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 << endl; // 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 << endl; return 0; } |
Original Array: 10 20 30 30 20 10 10 20 New Array: 10 99 30 30 99 10 10 99
Time Complexity: O(N)
Auxilliary Space: O(1)
How to Replace a Value in an Array in C++?
In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to replace a value in an array in C++.
Example:
Input: arr: {10 20 30 30 20 10 10 20} Element_to_replace= 20 replacement=99 Output: Array after replacement: {10 99 30 30 99 10 10 99}