C++ is not a functional programming language. C++ has its roots in the procedural and object-oriented programming. So it’s quite surprising that programming in a functional style becomes more and more important in C++.

C began in the early 70th of the last century. 1998 the first C++ standard was published. 13 years later the area of modern C++ began with C++11. A lot more interesting than the raw numbers is the fact that each of these three steps stands for a different way of solving problems. In C you think in procedures and structures. C++ introduces with object-orientation and generic programming a new kind of abstraction. With C++11 we got the functional programming style.

Functional programming

A will only say a few words about functional programming because I will and can not explain the concept of functional programming in a short remark. Only that much. I use the code snippet the pendants in C++ to the typical functions in functional programming: map, filter, and reduce. These are the functions std::transform, std::remove_if, and std::accumulate.

std::vector<int> vec{1,2,3,4,5,6,7,8,9};
std::vector<std::string> str{"Programming","in","a","functional","style."};

[](int i){ return i*i; }); // {1,4,9,16,25,36,49,64,81}

auto it= std::remove_if(vec.begin(),vec.end(),
[](int i){ return ((i < 3) or (i > 8)) }); // {3,4,5,6,7,8}
auto it2= std::remove_if(str.begin(),str.end(),
[](string s){ return (std::lower(s[0])); }); // "Programming"

std::accumulate(vec.begin(),vec.end(),[](int a,int b){return a*b;}); // 362880
[](std::string a,std::string b){return a + ":"+ b;});
// "Programming:in:a:functional:style."

I apply in the code snippet two powerful features of functional programming. Both are now mainstream in modern C++: automatic type deduction with auto and lambda-functions.


Tags , , , , , , , , , , , , , , , , , ,

Leave a Reply

Want to see your ugly mug by your comment? Get a free custom avatar at Gravatar.