C++
for_each
std::cout
programming
tutorial

How do I use for_each to output to cout?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Yes, you can use std::for_each to print values to std::cout. The usual pattern is to pass a lambda or function object that writes each element, though in modern C++ a range-based for loop is often simpler when the goal is only output.

Basic std::for_each with a Lambda

The direct approach is a lambda that prints each item:

cpp
1#include <algorithm>
2#include <iostream>
3#include <vector>
4
5int main() {
6    std::vector<int> values{1, 2, 3, 4};
7
8    std::for_each(values.begin(), values.end(), [](int value) {
9        std::cout << value << ' ';
10    });
11
12    std::cout << '\n';
13}

This works because std::for_each simply applies the callable to every element in the range.

Printing with Formatting State

Sometimes output needs separators without a trailing comma. A lambda can capture small state for that:

cpp
1#include <algorithm>
2#include <iostream>
3#include <string>
4#include <vector>
5
6int main() {
7    std::vector<std::string> words{"red", "green", "blue"};
8    bool first = true;
9
10    std::for_each(words.begin(), words.end(), [&](const std::string& word) {
11        if (!first) {
12            std::cout << ", ";
13        }
14        std::cout << word;
15        first = false;
16    });
17
18    std::cout << '\n';
19}

This is a reasonable use of std::for_each because the callable contains the formatting rule.

Using a Function Object

If the formatting logic is reused, a function object can be clearer than an inline lambda:

cpp
1#include <algorithm>
2#include <iostream>
3#include <vector>
4
5struct BracketPrinter {
6    void operator()(int value) const {
7        std::cout << '[' << value << "] ";
8    }
9};
10
11int main() {
12    std::vector<int> values{7, 8, 9};
13    std::for_each(values.begin(), values.end(), BracketPrinter{});
14    std::cout << '\n';
15}

This style is helpful when printing behavior belongs to a reusable utility.

Alternatives That May Be Clearer

Even though std::for_each works, it is not always the best answer.

A range-based for loop is often the clearest:

cpp
1for (int value : values) {
2    std::cout << value << ' ';
3}
4std::cout << '\n';

If you want very direct streaming with a separator, std::copy plus std::ostream_iterator is also common:

cpp
1#include <algorithm>
2#include <iterator>
3#include <iostream>
4#include <vector>
5
6int main() {
7    std::vector<int> values{1, 2, 3, 4};
8    std::copy(values.begin(), values.end(),
9              std::ostream_iterator<int>(std::cout, " "));
10    std::cout << '\n';
11}

That version is concise, though less flexible once formatting becomes more complex.

When std::for_each Is a Good Fit

Use std::for_each when you already have an algorithm-oriented style, or when the callable does something slightly richer than plain printing. Examples include counting elements while printing them, formatting records, or logging with small side effects.

If all you need is to display a container, the simplest readable form is usually the best. In many codebases, that means a range-based for.

Output Performance Notes

Printing itself is usually much slower than the loop construct. In other words, choosing std::for_each versus a for loop rarely changes performance in a meaningful way.

What does matter is stream flushing. Prefer a plain newline character unless you specifically need a flush:

cpp
std::cout << '\n';

Using std::endl forces a flush, which can slow down output-heavy code.

Common Pitfalls

One common mistake is forgetting to include the correct headers. std::for_each needs algorithm, and std::ostream_iterator needs iterator.

Another issue is using a lambda capture carelessly. Capturing a large object by value just to print a few elements is unnecessary overhead. Capture only what the callable actually needs.

Developers also sometimes expect std::for_each to insert separators automatically. It does not. If you need commas or custom formatting, you must handle that logic yourself.

Finally, do not overcomplicate simple output. If a range-based for loop reads better, use it. C++ algorithms are valuable, but readability still wins.

Summary

  • 'std::for_each can print to std::cout by calling a lambda or function object for each element.'
  • A lambda is the simplest way to add per-element output logic.
  • Use captured state when you need custom separators or formatting.
  • Consider std::copy with std::ostream_iterator or a range-based for loop for simpler output tasks.
  • Prefer clarity over cleverness, because printing code should be easy to scan and maintain.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.