I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com

replace

Replaces elements that have a special value with another value
+ View version details

Key Facts

Gyroscopic Couple: The rate of change of angular momentum (\inline \tau) = \inline I\omega\Omega (In the limit).
  • \inline I = Moment of Inertia.
  • \inline \omega = Angular velocity
  • \inline \Omega = 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() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class ForwardIterator, class Type >
   void replace(
      ForwardIterator first, 
      ForwardIterator last,
      const Type& oldVal, 
      const Type& newVal
   );

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 A forward iterator pointing to the position one past the final element in the range from which elements are being replaced
oldVal The old value of the elements being replaced
newVal The new value being assigned to the elements with the old value

Description

Replace function replaces all value equal to oldVal (using operator== of the iterator) by the value newVal in a range. The replacement is done by using operator= of the iterator.

Return Value

None.

Complexity

The complexity is linear; there are (last - first) comparisons for equality and at most (last - first) assignments of new values.
Example:
Example - replace algorithm
Problem
This program illustrates the use of the STL replace() algorithm to replace all copies of a given value from a vector of integers with another value.
Workings
#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
int main()
{
  int a[] = {1, 2, 2, 3, 4, 5, 2, 3};
  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 copies of the value 2 with 222.";
  replace(v.begin(), v.end(), 2, 222);
 
  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 3

Now we replace all copies of the value 2 with 222.

Here are the revised contents of the vector:
1 222 222 3 4 5 222 3