Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
Math code snippet to make all elements in a container positive.
There are multiple ways to implement MakeAbs:
- Using an algorithm (preferred [1][2])
- Using a for-loop
Note: I did not find any way to refrain from writing a functor (for example, by using std::ptr_fun) as shown in the lines below...
std::transform(v.begin(),v.end(),v.begin(),std::abs); //Does not work
std::transform(v.begin(),v.end(),v.begin(),&std::abs); //Does not work
std::transform(v.begin(),v.end(),v.begin(),std::ptr_fun(&std::abs)); //Does not work
std::transform(v.begin(),v.end(),v.begin(),std::ptr_fun(std::abs)); //Does not work
|
- 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.'
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.
