Open In App

How to Replace an Element in a List in C++?

Last Updated : 15 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a std::list represents a doubly linked list, a sequence container that stores data in non-contiguous memory. In this article, we will learn how to replace a specific element in a list using C++.

Example:

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

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

Replace Specific Element in a List in C++ STL

In C++, we can easily replace an element in the std::list by using the std::replace() function from the <algorithm> library that replaces a given value with another new value. We need to pass the beginning and ending iterators of the list to the replace() function along with the element you want to replace and the new element.

Syntax of std::replace()

replace(begin, end, old_value, new_value);

C++ Program to Replace an Element in a List

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

C++
// C++ program to illustrate how to replace a specific
// element in a list

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

int main()
{
    // Creating a list of integers
    list<int> nums = { 10, 20, 30, 60, 40, 12, 50 };

    // Elements to replace
    int oldElement = 60;
    int newElement = 100;

    // Replacing the old element with the new element
    replace(nums.begin(), nums.end(), oldElement,
            newElement);

    // Printing the list after replacement
    cout << "List after replacement : ";
    for (int num : nums) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

Output
List after replacement : 10 20 30 100 40 12 50 

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




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads