Skip to content

Latest commit

 

History

History
98 lines (59 loc) · 3.69 KB

File metadata and controls

98 lines (59 loc) · 3.69 KB

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

 

There are multiple ways to implement MakeAbs:

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

 

 

 

 

 

 


#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

 

 

 

 

 

MakeAbs using a for-loop

 


#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]);   } }

 

 

 

 

 

 

  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.'