(C++) std::replace\_if
January 7, 2018 · View on GitHub
(C++) std::replace_if
std::replace_if is an STL algorithm to replace elements of a sequence (on a std::vector, for example) that satisfy a certain predicate. Use std::replace if no predicate is needed (that is: a certain value must always be replaced).
Prefer algorithms over hand-written loops [1-3]. Exercise #9: No for-loops shows how to remove hand-written loops.
Example
The code below shows how to replace all values that are negative to zero:
#include <algorithm> #include <numeric> #include <vector> //From http://www.richelbilderbeek.nl/CppReplaceNegativeByZero.htm void ReplaceNegativeByZero(std::vector<int>& v) { std::replace_if(v.begin(),v.end(), std::bind2nd(std::less<int>(),0),0); }
replace_if function definition
Simplified and modified from the STL that ships with C++ Builder 6.0:
template < class ForwardIter, class Predicate, class Tp > void replace_if( ForwardIter first, const ForwardIter last, const Predicate pred, const Tp& newvalue) { for ( ; first != last; ++first) { if (pred(*first)) { *first = newvalue; } } }
External links
References
- Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1 : 'Prefer algorithms over loops'
- Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 84: 'Prefer algorithm calls to handwritten loops.'
- Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 88: 'Prefer function objects over functions as algorithm and comparer arguments.'