![]() |
In C++, Vectors are similar to arrays but unlike the arrays, they can change their size dynamically when the elements are inserted or deleted. We might encounter use cases where we will have to replace all of the occurrences of a specific element in a vector. In this article, we will explore how to replace all the occurrences of a specific element in C++. Example: Input: myVector = {20,30,10,50, 10} Output: myVector = {20, 30, 100 ,50, 100} // replaced all occurrence of 10 with 100 Replace All Occurrences of an Element in a Vector in C++The Standard Template Library (STL) of C++ provides a std::replace() function which can be used to replace all the occurrences of a specific element in the given range. We have to pass the beginning and ending iterators of the vector 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 VectorC++
Output
Original Vector: 20 30 10 50 20 30 10 50 Updated Vector: 20 30 100 50 20 30 100 50 Time Complexity: O(N), where N is the total number of elements in the vector |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |