Skip to main content

9.3) Algorithm Examples: Replacing Values


replace requires a pair of iterators, a value to be replaced and its replacement:

vector<int> v;
...
replace(v.begin(), v.end(), 0, 1);   // replaces 0 with 1

replace_if requires a pair of iterators, a predicate function that returns true if a value should be replaced, and a replacement value:

bool is_negative(int value)
{
  return value < 0;
}
...
replace_if(v.begin(), v.end(), is_negative, 0);

See replace.cpp and replaceif.cpp for complete examples.