replace_if
Replaces elements that match a criterion with another value
Key Facts
Gyroscopic Couple: The rate of change of angular momentum () = (In the limit).- = Moment of Inertia.
- = Angular velocity
- = Angular velocity of precession.
Blaise Pascal (1623-1662) was a French mathematician, physicist, inventor, writer and Catholic philosopher.
Leonhard Euler (1707-1783) was a pioneering Swiss mathematician and physicist.
Definition
The replace_if() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.Interface
#include <algorithm> template < class ForwardIterator, class Predicate, class Type > void replace_if( ForwardIterator first, ForwardIterator last, Predicate pred, const Type& val );Parameters:
Parameter | Description |
---|---|
first | A forward iterator pointing to the position of the first element in the range from which elements are being replaced |
last | An iterator pointing to the position one past the final element in the range from which elements are being replaced |
pred | The unary predicate that must be satisfied is the value of an element is to be replaced |
val | The new value being assigned to the elements whose old value satisfies the predicate |
Description
Replace_if function does the same thing that the replace function but uses thepred
predicate instead of operator==
.Complexity
The complexity is linear; there arelast - first
applications of pred
and at most last - first
assignments.References
Example:
Example - replace_if algorithm
Problem
This program illustrates the use of the STL replace_if() algorithm to replace all copies of a given value in a vector of integers that satisfy a given predicate with another value.
Workings
#include <iostream> #include <vector> #include <algorithm> using namespace std; /* Determines if an integer is divisible by 3. n contains an integer. Returns true if n is divisible by 3, and otherwise false. */ bool isDivisibleByThree ( int n //in ) { return (n%3 == 0); } int main() { int a[] = {1, 2, 2, 3, 4, 5, 2, 6}; vector<int> v(a, a+8); cout <<"\nHere are the values in the vector:\n"; for (vector<int>::size_type i=0; i<v.size(); i++) cout <<v.at(i)<<" "; cout <<"\nNow we replace all values divisble by 3 with 123."; replace_if(v.begin(), v.end(), isDivisibleByThree, 123); cout <<"\nHere are the revised contents of the vector:\n"; for (vector<int>::size_type i=0; i<v.size(); i++) cout <<v.at(i)<<" "; return 0; }
Solution
Output:
Here are the values in the vector:
1 2 2 3 4 5 2 6 Now we replace all values divisble by 3 with 123. Here are the revised contents of the vector:
1 2 2 123 4 5 2 123
1 2 2 3 4 5 2 6 Now we replace all values divisble by 3 with 123. Here are the revised contents of the vector:
1 2 2 123 4 5 2 123
References