C++ Algorithm replace()C++ Algorithm replace() function is used to replace all value equal to old_value by the value new_value in the range [first, last). This function examines each element in the range and replaces it if it matches a specified value. SyntaxParameterfirst: A forward iterator pointing to the initial position in the range from which elements are being replaced. last: A forward iterator pointing to the final position in the range from which elements are being replaced. old_value: The old value of the elements to be replaced. new_value: The new value being assigned to the elements with the old value. Return valueNone ComplexityComplexity is linear in the distance within first and last. It compares each element and assigns to those matching. Data racesThe objects in the range [first1, last1) are accessed and potentially modified. Exception safetyThrows an exception if any of the function calls the assignments or the operations on iterators throws an exception. Please note that invalid parameters cause an undefined behavior. Example 1Let's see the simple example to demonstrate the use of replace(): Output: 3,10,2,10,2, In the above example, element 1 of vector v is replaced by 10. Example 2Let's see another simple example: Output: The original vector v1 is: ( 4 7 7 7 0 5 7 1 6 9 3 7 8 2 ). The vector v1 with a value 700 replacing that of 7 is: ( 4 700 700 700 0 5 700 1 6 9 3 700 8 2 ). In the above example, replace() finds all the elements from vector v1 matches with 7 and replace it with the 700. Example 3Let's see another simple example: Output: v : 1 4 3 2 3 10 7 9 3 8 After replacing 3 with 6 v : 1 4 6 2 6 10 7 9 6 8 Example 4Let's see another simple example: Output: myvector contains: 10 99 30 30 99 10 10 99 Next TopicC++ Algorithm |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India