Open In App

How to Replace All Occurrences of an Element in a List in C++?

In C++, a std::list that represents a doubly linked list is a sequence containers that allow non-contiguous memory allocation. In this article, we will learn how to replace all the occurrences of a specific element in a list using C++ STL.

Example:

Input: 
myList = {10, 20, 30, 10, 30, 30, 50};
oldElement = 30;
newElement = 100;

Output:
myList = {10, 20, 100, 10, 100, 100, 50};

Replacing All Occurrences of a Specific Element in a List in C++

To replace all occurrences of a specific element in a std::list, we can use the std::replace() function from the <algorithm> library that replaces all occurrences of a specific value in a range with another value. We just have to pass the beginning and ending iterators of the list to the replace() function along with the element we want to replace and the new element.

Syntax of std::replace()

replace(begin, end, oldValue, newValue)

C++ Program to Replace All Occurrences of an Element in a List

The below example demonstrates the use of the std::replace() function to replace all occurrences of a specific element in a std::list in C++ STL.

// C++ program to illustrate how to replace all the
// occurences of a specific element

#include <algorithm>
#include <iostream>
#include <list>
using namespace std;

int main()
{
    // intitialize a list
    list<int> myList = { 10, 20, 30, 10, 30, 30, 50 };

    // Declare the value you want to replace
    int oldVal = 30;
    int newVal = 100;

    // Print the original list
    cout << "Original List: ";
    for (int element : myList) {
        cout << element << " ";
    }
    cout << endl;

    // Replace all occurrences of oldValue with newValue
    replace(myList.begin(), myList.end(), oldVal, newVal);

    // Print the updated list
    cout << "Updated List: ";
    for (int element : myList) {
        cout << element << " ";
    }
    cout << endl;

    return 0;
}

Output
Original List: 10 20 30 10 30 30 50 
Updated List: 10 20 100 10 100 100 50 

Time Complexity: O(n), where n is the number of elements in the list.
Auxiliary Space: O(1)

Article Tags :