Functional Programming in C++: From A to Z — A Practical Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Functional Programming in C++: From A to Z



Many developers familiar with Python or JavaScript are accustomed to powerful functional programming tools: lambdas, map, filter, reduce. But did you know that C++ offers equally flexible capabilities for a functional style? In this article, we will explore functional programming in C++ from basic concepts to advanced techniques. You will learn how to write more concise, safe, and expressive code using modern C++11/14/17 features.



1. Fundamentals of the Functional Approach: Lambda Expressions and std::function



Functional programming in C++ begins with lambda expressions. They allow you to create anonymous functions right at the point of use. The syntax of a lambda is simple:



// Basic lambdaauto sum = [](int a, int b) -> int { return a + b; };std::cout << sum(5, 3); // 8

// Lambda with variable captureint multiplier = 3;auto multiply = [multiplier](int x) { return x * multiplier; };std::cout << multiply(7); // 21


A key feature of lambdas is context capture. You can capture variables by value ([=]), by reference ([&]), or in a combined manner. This is the basis of closures, which are fundamental to the functional style.



To store and pass lambdas, std::function is used — a polymorphic wrapper for callable objects:



#include <functional>

std::function<int(int, int)> operation;

operation = [](int a, int b) { return a + b; };std::cout << operation(10, 20); // 30

operation = [](int a, int b) { return a * b; };std::cout << operation(10, 20); // 200


Tip: Use auto for lambdas if you don't need to store them as a type. std::function adds a small overhead, so it should only be used when polymorphism is required.



2. STL Algorithms: map, filter, reduce by Hand



C++ does not have built-in map, filter, reduce functions like Python, but the STL provides powerful algorithms that replace them. Let's look at the main ones:



2.1. Map — Transforming Elements

Instead of map, use std::transform:



#include <algorithm>#include <vector>

std::vector<int> numbers = {1, 2, 3, 4, 5};std::vector<int> squares(numbers.size());

std::transform(numbers.begin(), numbers.end(), squares.begin(), [](int n) { return n * n; });// squares: {1, 4, 9, 16, 25}


2.2. Filter — Filtering by Condition

The analog of filter is std::copy_if or std::remove_if (with subsequent removal):



std::vector<int> numbers = {1, 2, 3, 4, 5, 6};std::vector<int> evens;

std::copy_if(numbers.begin(), numbers.end(), std::back_inserter(evens), [](int n) { return n % 2 == 0; });// evens: {2, 4, 6}


2.3. Reduce — Folding a Collection

For reduce, use std::accumulate from <numeric>:



#include <numeric>

std::vector<int> numbers = {1, 2, 3, 4, 5};int sum = std::accumulate(numbers.begin(), numbers.end(), 0, [](int acc, int n) { return acc + n; });// sum = 15


Advanced example: Combining map, filter, and reduce for data processing:



std::vector<std::string> names = {"Alice", "Bob", "Charlie", "David"};// Get the sum of lengths of names starting with 'A' or 'C'int result = std::accumulate(names.begin(), names.end(), 0,    [](int acc, const std::string& name) {        if (name[0] == 'A' || name[0] == 'C') {            return acc + name.length();        }        return acc;                

Blogs

Book Recommendations