# (C++) MakeAbs

Math code snippet to make all elements in a container positive.

There are multiple ways to implement MakeAbs:

1. Using an algorithm (preferred )
2. Using a for-loop

## MakeAbs using an algorithm

 ``` #include #include #include #include template struct Abs : public std::unary_function {   const T operator()(const T& x) const { return std::abs(x); } }; void MakeAbs(std::vector& v) {   std::transform(v.begin(),v.end(),v.begin(),Abs()); } ```

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 ```

## MakeAbs using a for-loop

 ``` #include #include   void MakeAbs(std::vector& v) {   const int sz = v.size();   for (int i=0; i!=sz; ++i)   {     v[i] = std::abs(v[i]);   } } ```

## References

1. Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1 : 'Prefer algorithms over loops'
2. 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.' 