for_each Loop Example in C++

C++ for_each Loop Tutorial and Examples

The for_each loop is a versatile and powerful feature in C++ that allows you to iterate through elements in a collection or container and apply a specified operation to each element. It provides a concise and elegant way to process elements without the need for explicit indexing or manual iteration. In this article, we will explore the for_each loop and demonstrate how to use it effectively with various code examples.

Basic Syntax

The for_each loop is part of the Standard Template Library (STL) and is defined in the <algorithm> header. It takes three arguments: the beginning iterator of the collection, the ending iterator of the collection, and a function or callable object to apply to each element.

The syntax of the for_each loop is as follows:

template <class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function fn);

Here’s a quick run-down of the parameter list of the for_each function.

  • InputIterator first: An iterator pointing to the beginning of the collection.
  • InputIterator last: An iterator pointing to the end of the collection (one past the last element).
  • Function fn: A function or callable object to apply to each element.

Let’s dive into some examples to illustrate how to use the for_each loop.

Example 1: Printing Elements

#include <iostream>
#include <algorithm>
#include <vector>

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

    // Using a lambda function to print each element.
    std::cout << "Printing elements using for_each: ";
    std::for_each(numbers.begin(), numbers.end(), [](int num) {
        std::cout << num << " ";
    });

    return 0;
}

Output:

Printing elements using for_each: 1 2 3 4 5

In this example, we create a std::vector<int> named numbers and use the for_each loop to print each element using a lambda function.

Example 2: Modifying Elements

The for_each loop can also be used to modify elements in the collection.

#include <iostream>
#include <algorithm>
#include <vector>

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

    // Using a lambda function to square each element.
    std::for_each(numbers.begin(), numbers.end(), [](int& num) {
        num *= num;
    });

    // Printing modified elements.
    std::cout << "Modified elements: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }

    return 0;
}

Output:

Modified elements: 1 4 9 16 25

In this example, we use the for_each loop with a lambda function to square each element in the numbers vector.

Example 3: Working with Custom Objects

The for_each loop can be used with custom objects as well.

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

class Person {
public:
    Person(std::string name, int age) : name(name), age(age) {}

    void celebrateBirthday() {
        age++;
    }

    void displayInfo() const {
        std::cout << name << " - " << age << " years old\n";
    }

private:
    std::string name;
    int age;
};

int main() {
    std::vector<Person> people = {Person("Alice", 25), Person("Bob", 30), Person("Charlie", 22)};

    // Using a lambda function to celebrate the birthday of each person.
    std::for_each(people.begin(), people.end(), [](Person& person) {
        person.celebrateBirthday();
    });

    // Displaying updated information.
    std::cout << "Updated information after celebrating birthdays:\n";
    std::for_each(people.begin(), people.end(), [](const Person& person) {
        person.displayInfo();
    });

    return 0;
}

Output:

Updated information after celebrating birthdays:
Alice - 26 years old
Bob - 31 years old
Charlie - 23 years old

In this example, we use the for_each loop with a lambda function to celebrate the birthday of each Person object in the people vector.

Example 4: Using Function Objects (Functors)

Apart from lambda functions, you can use function objects (functors) with the for_each loop. Function objects are classes that behave like functions when instances of those classes are called.

#include <iostream>
#include <algorithm>
#include <vector>

// Functor to print the square of a number.
struct SquarePrinter {
    void operator()(int num) const {
        std::cout << num * num << " ";
    }
};

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

    // Using the SquarePrinter functor.
    std::cout << "Squared elements using functor: ";
    std::for_each(numbers.begin(), numbers.end(), SquarePrinter());

    return 0;
}

Output:

Squared elements using functor: 1 4 9 16 25

Here, we define a SquarePrinter functor and use it with the for_each loop to print the square of each element in the numbers vector.


The for_each loop in C++ is a valuable tool for iterating through collections and applying operations to each element efficiently. Whether you use lambda functions or function objects, the for_each loop simplifies your code and enhances readability. By incorporating it into your C++ projects, you can streamline the process of working with collections and focus on implementing the logic that truly matters.

Remember to include the <algorithm> header when using for_each, and explore the vast potential of this powerful loop in your C++ programs. Happy coding!

Similar Posts