C++ Algorithm replace_copy_if()C++ Algorithm replace_copy_if() function is used to make a copy of the range [first, last) to the range beginning at result, placing those for which pred returns true by new_value. It uses predicate pred instead of operator== to compare the elements. This function examines each element in a source range and replaces it if it satisfies a specified predicate while copying the result into a new destination range. SyntaxParameterfirst: An input iterator pointing to the initial position in the range from which elements are being replaced. last: A input iterator pointing to the final position in the range from which elements are being replaced. result: An output iterator pointing to the first element of the range where the resulting sequence is stored. pred: The unary predicate that must be satisfied if the value of an element is to be replaced. old_value: The old value of the element being replaced. new_value: The new value assigned to the element with the old value. Return valueThe replace_copy_if() function returns an output iterator pointing to the position that points to the last element written in the result sequence. ComplexityComplexity is linear in the distance between first and last: Applies pred and performs an assignment for each element. Data racesThe objects in the range [first1, last1) are accessed. The objects in the range within result and the returned value are modified. Exception safetyThis function throws an exception if any of pred, the element 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_copy_if(): Output: 10,10,2,10,2, Example 2Let's see another simple example: Output: Before replace_copy_if: 1 2 3 4 5 6 7 8 9 10 After replace_copy_if: 1 0 3 0 5 0 7 0 9 0 Example 3Let's see another simple example: Output: Numbers { 10 20 10 15 12 7 9 10 } Total number of elements copied to Result = 8 Result { 30 30 30 30 30 7 9 30 } Example 4Let'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 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ). The vector v1 with values of 70 replacing those greater than 6 in the 1st half & copied into the 2nd half is: ( 4 7 7 7 0 5 7 1 6 9 3 7 8 2 4 70 70 70 0 5 70 1 6 70 3 70 70 2 ). A list copy of vector v1 with the value -1 replacing those greater than 6 is: ( 4 -1 -1 -1 0 5 -1 1 6 -1 3 -1 -1 ). 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