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.
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:
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:
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:
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:
If you want very direct streaming with a separator, std::copy plus std::ostream_iterator is also common:
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:
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_eachcan print tostd::coutby 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::copywithstd::ostream_iteratoror a range-basedforloop for simpler output tasks. - Prefer clarity over cleverness, because printing code should be easy to scan and maintain.
Related reading
- How do I use the new C17 execution policies?
- How do nicely concat asynchronous network requests in Qt
- How do you declare an interface in C++?
- How do you pass a function as a parameter in C?
- How does one transfer CUDA constant memory in tensorflow's C API
- How does stdsort work for list of pairs?
- How is nth_element Implemented?
- How is the new asynchronous model in C26 different from existing models?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.