Math code snippet to make all elements in a container positive.
There are multiple ways to implement MakeAbs:
#include <algorithm> #include <cmath> #include <functional> #include <vector> template <class T> struct Abs : public std::unary_function<T,T> { const T operator()(const T& x) const { return std::abs(x); } }; void MakeAbs(std::vector<int>& v) { std::transform(v.begin(),v.end(),v.begin(),Abs<int>()); }
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
#include <cmath> #include <vector> void MakeAbs(std::vector<int>& v) { const int sz = v.size(); for (int i=0; i!=sz; ++i) { v[i] = std::abs(v[i]); } }
- 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.'