C++

'std::for_each' Is Not a Member of 'std' Fix

std::for_each lives in one header, <algorithm> - and in the sweep probed here, covering all 106 standard headers in this library's header set, only 5 other headers pull it in on the side, so the textbook <vector> program fails outright. This name is one of the oldest in its family - it dates to C++98, so no standard setting rescues or causes this error - and its diagnostic is as plain as its siblings': not one of the 100 failing sole-header contexts decorates the error with a suggestion. This guide pins down the failing shapes, why the call returns the function object it was given, why the counted sibling for_each_n is younger than the classic call, and the include that fixes the case by rule.

Written December 3, 2026 · Tested with GCC 13.3.0 · 28 min read

By the end of this guide
  • The error: the include is missing
  • The textbook version fails too - with no suggestion at all
  • The suggestion in the sweep: there is none
  • Neighboring headers: 100 fail plainly, none offers a suggestion, and 5 rescue it by accident

Written December 3, 2026

Tested with GCC 13.3.0

What this guide is

std::for_each is a function template defined in the header <algorithm>. It applies a function object to each element of a range, in order, and returns that function object: over 1, 2, 3, 4, 5, a summing object comes back holding 15, which is how the call hands back the state the function built up while it ran. If the function returns a value, the value is ignored. The range needs only input iterators, and if those iterators are mutable the function may modify the elements through them. The classic call dates to C++98, has an execution-policy overload since C++17, and has been usable in constant expressions since C++20. Its counted sibling, std::for_each_n, applies the function to the first counted elements instead and dates only to C++17.

Because the function lives in <algorithm> - not in a container's header - 'for_each' is not a member of 'std' is the missing include, and naming that cause is the first step:

  • The #include <algorithm> line is missing, and no other header in the file pulls the name in transitively. For this error, in the contexts probed here, that second clause rarely saves anyone: in the sweep below, only 5 of the other 105 headers in the library's header set pull the name in on the side, so most files without <algorithm> do reach this error.

For this name the missing include is also the only cause of the error. std::for_each starts at C++98, so no standard setting produces this wording for the classic call: a file compiled as C++98 with <algorithm> included compiles and runs, as the versions section below shows. That sets this name apart from its younger siblings in this family, whose errors have a second, standard-based cause. The pieces layered on top still have floors of their own - the execution-policy overload needs C++17, constant-expression use needs C++20, and the counted sibling std::for_each_n needs C++17 - and those floors belong to the added pieces, not to the classic call.

This name's diagnostic is also as plain as its siblings': in the sweep below, not one of the 100 failing sole-header contexts decorates the error with a did you mean tail. There is no wrong name to follow - but there is also no hint in the diagnostic about where the right name lives. The sweep covers every one of the 106 standard headers in this library's header set, compiled as the only header in the program, and the rescue set has only 6 entries, because in this library the name is declared by a header that very little of the library includes.

The error: the include is missing

This program applies the call over 1, 2, 3, 4, 5 with a summing object, but includes only <limits>:

C++
#include <limits>
struct Sum { int total = 0; void operator()(int n) { total += n; } };
int main() {
    int a[5] = {1, 2, 3, 4, 5};
    Sum s = std::for_each(a, a + 5, Sum());
    return 0;
}
Output
-std=c++20 a_limits.cpp -o a_limits_prog
a_limits.cpp: In function 'int main()':
a_limits.cpp:5:18: error: 'for_each' is not a member of 'std'
    5 |     Sum s = std::for_each(a, a + 5, Sum());
      |                  ^~~~~~~~

Read it in full: one plain error line - no suggestion tail rides on it, there are no note lines, and there are no help lines. Nothing in the diagnostic names <algorithm> or points anywhere at all. The same program with no include at all fails the same way:

Output
-std=c++20 n_none.cpp -o n_none_prog
n_none.cpp: In function 'int main()':
n_none.cpp:4:18: error: 'for_each' is not a member of 'std'
    4 |     Sum s = std::for_each(a, a + 5, Sum());
      |                  ^~~~~~~~

The textbook version fails too - with no suggestion at all

The version most often written first - sum a vector with a lambda that captures the running total - produces an error in this library, without <algorithm>, and the error is the same plain line:

C++
#include <iostream>
#include <vector>
int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    int total = 0;
    std::for_each(v.begin(), v.end(), [&total](int n) { total += n; });
    std::cout << total << "\n";
    return 0;
}
Output
-std=c++20 t_textbook.cpp -o t_textbook_prog
t_textbook.cpp: In function 'int main()':
t_textbook.cpp:6:10: error: 'for_each' is not a member of 'std'
    6 |     std::for_each(v.begin(), v.end(), [&total](int n) { total += n; });
      |          ^~~~~~~~

Nothing rescues the call here: <vector> does not pull the algorithm in - in the sweep below it fails for this name, with this same plain error. And there is no suggestion to misread: this name's error offers nothing, so the only move it leaves is the right one. A program that uses std::for_each includes <algorithm>, whether or not it happens to compile without it. A sole <algorithm> file makes the point in miniature - the call compiles and runs with nothing else in sight:

Terminal
-std=c++20 i_algorithm.cpp -o i_algorithm_prog
$ ./i_algorithm_prog

The suggestion in the sweep: there is none

The textbook file is typical, not unlucky. In the sweep below, all 100 failing sole-header contexts fail with the plain error line alone - not one of them carries a did you mean tail. That is a property of this name in this library: no header in the set declares a name close enough to for_each, in a context where the algorithm itself is missing, for the compiler to offer a guess.

So for this name the diagnostic gives the reader exactly one piece of information - the name is not a member of std in this file - and the fix has to come from knowing the declaring header, not from reading the error. The move is the same either way: name the declaring header.

Neighboring headers: 100 fail plainly, none offers a suggestion, and 5 rescue it by accident

In a sweep where each of the 106 standard headers in this library's header set was compiled as the only header in a program that applies the call over 1, 2, 3, 4, 5 with a summing function object and requires the total 15 back, the outcome splits two ways - the plain failure, or a rescue. Every diagnostic component was classified separately - the error line, any suggestion tail on it, any note lines, and any help lines. These 100 headers all fail with the plain is not a member of 'std' error line - no suggestion tail on that line, no note lines, and no help lines:

  • <any>
  • <array>
  • <atomic>
  • <barrier>
  • <bit>
  • <bitset>
  • <cassert>
  • <ccomplex>
  • <cctype>
  • <cerrno>
  • <cfenv>
  • <cfloat>
  • <charconv>
  • <cinttypes>
  • <ciso646>
  • <climits>
  • <clocale>
  • <cmath>
  • <codecvt>
  • <compare>
  • <complex>
  • <concepts>
  • <condition_variable>
  • <coroutine>
  • <csetjmp>
  • <csignal>
  • <cstdalign>
  • <cstdarg>
  • <cstdbool>
  • <cstddef>
  • <cstdint>
  • <cstdio>
  • <cstdlib>
  • <cstring>
  • <ctgmath>
  • <ctime>
  • <cuchar>
  • <cwchar>
  • <cwctype>
  • <deque>
  • <exception>
  • <expected>
  • <filesystem>
  • <format>
  • <forward_list>
  • <fstream>
  • <future>
  • <initializer_list>
  • <iomanip>
  • <ios>
  • <iosfwd>
  • <iostream>
  • <istream>
  • <iterator>
  • <latch>
  • <limits>
  • <list>
  • <locale>
  • <map>
  • <memory>
  • <memory_resource>
  • <mutex>
  • <new>
  • <numbers>
  • <numeric>
  • <optional>
  • <ostream>
  • <queue>
  • <random>
  • <ranges>
  • <ratio>
  • <scoped_allocator>
  • <semaphore>
  • <set>
  • <shared_mutex>
  • <source_location>
  • <span>
  • <spanstream>
  • <sstream>
  • <stack>
  • <stacktrace>
  • <stdexcept>
  • <stdfloat>
  • <stop_token>
  • <streambuf>
  • <string>
  • <string_view>
  • <syncstream>
  • <system_error>
  • <thread>
  • <tuple>
  • <type_traits>
  • <typeindex>
  • <typeinfo>
  • <unordered_map>
  • <unordered_set>
  • <utility>
  • <variant>
  • <vector>
  • <version>

A file with no include at all fails the plain way. Two entries deserve a pause. <limits> fails plainly: the header of the numeric limits declares nothing close enough to this name to trigger a guess. <ranges> fails plainly for the classic name: the C++20 ranges library has its own for-each name, and it does not bring this one in - that name gets its own section below. And <vector> - the header of the container this call most often reads - fails plainly, as the textbook section above shows.

No failing header in any shape produced a suggestion, a help line, or a different error.

And these headers rescue the program - it compiles and runs with no <algorithm> anywhere in the file:

  • <algorithm>
  • <chrono>
  • <execution>
  • <functional>
  • <regex>
  • <valarray>

The declaring header in this library sits underneath very little - a time header, a policy header, a function-object header, the regular-expression header, and the numeric-array header - so the rescue set runs to only 5 transitive entries. That is also why the failing set is nearly the whole library here: with 100 of the other 105 headers failing, the missing include shows itself in almost any file that does not name <algorithm>. <algorithm> - the home header - is on the rescue list by definition, not by transitivity, and the other 5 rescues are this library version's behavior, not a guarantee.

The fix

Add the header:

C++
#include <algorithm>
#include <iostream>
#include <vector>
struct Sum { int total = 0; void operator()(int n) { total += n; } };
int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    Sum s = std::for_each(v.begin(), v.end(), Sum());
    std::cout << "result " << s.total << "\n";
    return 0;
}
Terminal
-std=c++20 h_fixed.cpp -o h_fixed_prog
$ ./h_fixed_prog
result 15

One include, <algorithm>, declares the function - and the textbook program prints result 15: the summing object came back holding the total of 1, 2, 3, 4, 5. The name is now declared by a header the file names itself, instead of by an internal include of one of the 5 rescuing headers that a different library version is free to rearrange. For a file that does fail - the <limits> shape above, or any other - the same one include is the whole fix, at every standard level: this name has no floor case, as the versions section below shows.

What the call does: it applies the function to every element, in order, and returns the function

The call's whole result is the function object it returns, and its defining choices are the order it keeps and the state it hands back: the function is applied to each element in order, starting from the first, the object is moved into the call, and the object that comes back carries whatever the applications accumulated - the object the caller passed in is left as it was. The counted sibling, std::for_each_n, stops after the counted elements and returns an iterator instead. This program walks the shapes in order:

C++
#include <algorithm>
#include <iostream>
#include <vector>
struct Sum { int total = 0; void operator()(int n) { total += n; } };
int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    Sum in;
    Sum out = std::for_each(v.begin(), v.end(), in);
    std::cout << "state " << in.total << " " << out.total << "\n";
    std::vector<int> seen;
    std::for_each(v.begin(), v.end(), [&seen](int n) { seen.push_back(n); });
    std::cout << "order";
    for (int n : seen) std::cout << " " << n;
    std::cout << "\n";
    std::vector<int> m = {1, 2, 3};
    std::for_each(m.begin(), m.end(), [](int& n) { n *= 2; });
    std::cout << "mutated";
    for (int n : m) std::cout << " " << n;
    std::cout << "\n";
    int calls = 0;
    std::for_each(v.begin(), v.end(), [&calls](int) { ++calls; });
    std::cout << "calls " << calls << "\n";
    Sum ns;
    auto nit = std::for_each_n(v.begin(), 3, Sum());
    std::cout << "n-end " << (nit - v.begin()) << "\n";
    int nsum = 0;
    std::for_each_n(v.begin(), 3, [&nsum](int n) { nsum += n; });
    std::cout << "n " << nsum << "\n";
    int ecalls = 0;
    std::vector<int> empty;
    std::for_each(empty.begin(), empty.end(), [&ecalls](int) { ++ecalls; });
    std::cout << "empty " << ecalls << "\n";
    return 0;
}
Terminal
-std=c++20 r_semantics.cpp -o r_semantics_prog
$ ./r_semantics_prog
state 0 15
order 1 2 3 4 5
mutated 2 4 6
calls 5
n-end 3
n 6
empty 0

Read in order: the state line reports 0 15 - the summing object passed in still holds 0 after the call, because the function object is moved into the call, and the object the call returns holds the accumulated 15; reading the total off the passed object instead of the returned one is the classic way to lose the result of this call. The order line reports 1 2 3 4 5 - the classic overload applies the function in order, from the first element on. The mutated line reports 2 4 6 - a function that takes each element by reference writes back through the mutable iterators, doubling 1, 2, 3 in place. The calls line reports 5: over 5 elements the function is applied exactly 5 times - the documented count is exactly the length of the range, no more and no fewer. The n-end line reports 3 and the n line reports 6: the counted sibling applied its function to the first 3 elements only, summing 1, 2, 3, and returned an iterator at position 3 - where the classic call returns the function, the counted call returns where it stopped. The empty line reports 0: over an empty range the function is never applied, and the returned object comes back untouched.

The cost rule is the documented count: with a range of length N, the call makes exactly N applications of the function - one per element, in order for the classic overload.

Versions: no floor for the classic call - it dates to C++98

This call has no floor inside the probed set. std::for_each dates to C++98 - the cppreference page carries no since-C++11 marker on the classic overload, and its defect reports are applied to C++98, which only makes sense for a name that already existed there. The fixed programs in this guide are compiled as C++20, but the name is far older than that: with <algorithm> included, the same summing program compiled as C++98 compiles and runs, printing 15, and as C++11, C++14, C++17, C++20, and C++23 the same way:

C++
#include <algorithm>
#include <iostream>
struct Sum { int total; Sum() : total(0) {} void operator()(int n) { total += n; } };
int main() {
    int a[5] = {1, 2, 3, 4, 5};
    Sum s = std::for_each(a, a + 5, Sum());
    std::cout << s.total << "\n";
    return 0;
}
Terminal
-std=c++98 c_version98.cpp -o c_version98_prog
$ ./c_version98_prog
15

So this name's error has one cause, not two: a missing <algorithm>. A file that includes <algorithm> and still sees this error does not have a standard problem; the include is not reaching the file that names the call, or the name in the file is not this name. No standard upgrade fixes a missing include, and no include change is needed for an old standard - the two halves of the family's usual advice separate cleanly for this name.

The pieces layered on top of the classic call carry their own floors, and naming one splits in two when a reader tries it. The counted sibling is the clearest case: std::for_each_n starts at C++17, so with <algorithm> included it compiles and runs as C++17, printing 6 3 - the sum of the first 3 elements and the position it stopped at:

Terminal
-std=c++17 f_for_each_n17.cpp -o f_for_each_n17_prog
$ ./f_for_each_n17_prog
6 3

Compiled as C++14, the same program fails - and this time the diagnostic does carry a suggestion, pointing back at the classic call:

Output
-std=c++14 f_for_each_n14.cpp -o f_for_each_n14_prog
f_for_each_n14.cpp: In function 'int main()':
f_for_each_n14.cpp:7:20: error: 'for_each_n' is not a member of 'std'; did you mean 'for_each'?
    7 |     auto it = std::for_each_n(v.begin(), 3, [&total](int n) { total += n; });
      |                    ^~~~~~~~~~
      |                    for_each

That suggestion is a spelling guess, not the fix: std::for_each exists at C++14, and std::for_each_n does not - the counted call needs the standard raised to C++17, with the same <algorithm> include in place. This name does also have an execution-policy overload, since C++17 - and naming the policy with only <algorithm> included fails on the policy's name, not the algorithm's:

C++
#include <algorithm>
#include <vector>
struct Sum { int total = 0; void operator()(int n) { total += n; } };
int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    std::for_each(std::execution::seq, v.begin(), v.end(), Sum());
    return 0;
}
Output
-std=c++20 p_policy_algonly.cpp -o p_policy_algonly_prog
p_policy_algonly.cpp: In function 'int main()':
p_policy_algonly.cpp:6:24: error: 'std::execution' has not been declared
    6 |     std::for_each(std::execution::seq, v.begin(), v.end(), Sum());
      |                        ^~~~~~~~~

That wording - has not been declared, naming std::execution - is the missing-header shape, and here adding the header is the whole fix: add <execution> alongside <algorithm>, and the same call compiles and runs, because the policy overload of std::for_each exists - and unlike the classic overload, the policy form returns nothing, so there is no returned object to read a total from:

Terminal
-std=c++20 p_policy_both.cpp -o p_policy_both_prog
$ ./p_policy_both_prog

The policy form belongs to this name, and it carries the C++17 floor. Compiled as C++14, the same two-header program fails on the policy's name again - at that standard the policy names are not there to be declared:

Output
-std=c++14 p_policy_cpp14.cpp -o p_policy_cpp14_prog
p_policy_cpp14.cpp: In function 'int main()':
p_policy_cpp14.cpp:7:24: error: 'std::execution' has not been declared
    7 |     std::for_each(std::execution::seq, v.begin(), v.end(), Sum());
      |                        ^~~~~~~~~

And since C++20 the classic call is also usable in constant expressions - this program's check happens at compile time, and the assertion on the result is part of the build:

C++
#include <algorithm>
#include <array>
constexpr int check() {
    std::array<int, 5> a{1, 2, 3, 4, 5};
    int total = 0;
    std::for_each(a.begin(), a.end(), [&total](int n) { total += n; });
    return total;
}
static_assert(check() == 15);
int main() { return 0; }
Terminal
-std=c++20 c_constexpr20.cpp -o c_constexpr20_prog
$ ./c_constexpr20_prog

Compiled as C++17, the same program fails - the call is not a constant expression there, and the static assertion cannot hold:

Output
-std=c++17 c_constexpr17.cpp -o c_constexpr17_prog
c_constexpr17.cpp: In function 'constexpr int check()':
c_constexpr17.cpp:6:18: warning: call to non-'constexpr' function '_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = int*; _Funct = check()::<lambda(int)>]' [-Winvalid-constexpr]
    6 |     std::for_each(a.begin(), a.end(), [&total](int n) { total += n; });
      |     ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/13/algorithm:61,
                 from c_constexpr17.cpp:1:
/usr/include/c++/13/bits/stl_algo.h:3827:5: note: '_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = int*; _Funct = check()::<lambda(int)>]' declared here
 3827 |     for_each(_InputIterator __first, _InputIterator __last, _Function __f)
      |     ^~~~~~~~
c_constexpr17.cpp: At global scope:
c_constexpr17.cpp:9:23: error: non-constant condition for static assertion
    9 | static_assert(check() == 15);
      |               ~~~~~~~~^~~
c_constexpr17.cpp:9:20: error: 'constexpr int check()' called in a constant expression
    9 | static_assert(check() == 15);
      |               ~~~~~^~
c_constexpr17.cpp:3:15: note: 'constexpr int check()' declared here
    3 | constexpr int check() {
      |                ^~~~~

So C++17 is the floor for the counted sibling and the policy form, C++20 is the floor for constant-expression use - and no standard at any level rescues a missing include, while the classic call needs nothing beyond <algorithm> at any standard from C++98 up.

The neighboring names: five fail, one compiles outright

The names a reader most often reaches for alongside this one mostly live in <algorithm> too, and in a file whose only include is <vector> this family splits - five of the six names fail, and one compiles. std::find, which returns an iterator to the first element equal to a value, fails with a suggestion that points into the ranges library:

Output
-std=c++20 b_find_vector.cpp -o b_find_vector_prog
b_find_vector.cpp: In function 'int main()':
b_find_vector.cpp:5:20: error: 'find' is not a member of 'std'; did you mean 'std::ranges::find'?
    5 |     auto it = std::find(v.begin(), v.end(), 3);
      |                    ^~~~
In file included from /usr/include/c++/13/tuple:44,
                 from /usr/include/c++/13/bits/uses_allocator_args.h:38,
                 from /usr/include/c++/13/bits/memory_resource.h:41,
                 from /usr/include/c++/13/vector:80,
                 from b_find_vector.cpp:1:
/usr/include/c++/13/bits/ranges_util.h:499:30: note: 'std::ranges::find' declared here
  499 |   inline constexpr __find_fn find{};
      |                              ^~~~

std::copy, which copies a range into another range, is the split: in this library a sole <vector> file compiles it outright, with no <algorithm> anywhere - the container header pulls the name in on the side here, as this library version's behavior, not as a rule:

Output
-std=c++20 b_copy_vector.cpp -o b_copy_vector_prog

std::transform, which applies a function to a range and stores the results in a destination range, fails with the plain error:

Output
-std=c++20 b_transform_vector.cpp -o b_transform_vector_prog
b_transform_vector.cpp: In function 'int main()':
b_transform_vector.cpp:5:20: error: 'transform' is not a member of 'std'
    5 |     auto it = std::transform(v.begin(), v.end(), dest.begin(), [](int n) { return n * 2; });
      |                    ^~~~~~~~~

std::accumulate, which folds a range into a single value, fails with the plain error too - and it is the neighbor whose home is a different header altogether, <numeric>, so its fix is not this guide's header:

Output
-std=c++20 b_accumulate_vector.cpp -o b_accumulate_vector_prog
b_accumulate_vector.cpp: In function 'int main()':
b_accumulate_vector.cpp:5:18: error: 'accumulate' is not a member of 'std'
    5 |     int t = std::accumulate(v.begin(), v.end(), 0);
      |                  ^~~~~~~~~~

std::count, which counts the elements equal to a value, fails with a suggestion that points at a bit-counting function, not at any algorithm:

Output
-std=c++20 b_count_vector.cpp -o b_count_vector_prog
b_count_vector.cpp: In function 'int main()':
b_count_vector.cpp:5:19: error: 'count' is not a member of 'std'; did you mean 'popcount'?
    5 |     auto c = std::count(v.begin(), v.end(), 3);
      |                   ^~~~~
      |                   popcount

While std::sort, which orders a range in place, fails with the plain error:

Output
-std=c++20 b_sort_vector.cpp -o b_sort_vector_prog
b_sort_vector.cpp: In function 'int main()':
b_sort_vector.cpp:5:10: error: 'sort' is not a member of 'std'
    5 |     std::sort(v.begin(), v.end());
      |          ^~~~

No suggestion in this set names the declaring header: one names the ranges form of a neighbor, the other names a bit-counting function - both are spelling guesses, and neither is a member of this guide's family in the form offered. And the one name that compiles, std::copy, compiles by accident of this library's internal includes - the rule for it is the same <algorithm> as for the rest. The failing neighbors are shown here only as neighbors, not re-taught.

The neighboring names, fixed

Together the seven names take two headers between them - <algorithm> for six of them, <numeric> for std::accumulate, with <vector> covering only the containers they work on. The fixed neighbor program reports all seven operations over the range 1, 2, 3, 4, 5:

C++
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
struct Sum { int total = 0; void operator()(int n) { total += n; } };
int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    Sum s = std::for_each(v.begin(), v.end(), Sum());
    std::cout << "for_each " << s.total << "\n";
    auto f = std::find(v.begin(), v.end(), 3);
    std::cout << "find " << (f - v.begin()) << " " << *f << "\n";
    std::vector<int> dest(5);
    std::copy(v.begin(), v.end(), dest.begin());
    std::cout << "copy " << dest.front() << " " << dest.back() << "\n";
    std::vector<int> doubled(5);
    std::transform(v.begin(), v.end(), doubled.begin(), [](int n) { return n * 2; });
    std::cout << "transform";
    for (int n : doubled) std::cout << " " << n;
    std::cout << "\n";
    int acc = std::accumulate(v.begin(), v.end(), 0);
    std::cout << "accumulate " << acc << "\n";
    auto c = std::count(v.begin(), v.end(), 3);
    std::cout << "count " << c << "\n";
    std::vector<int> w = {5, 3, 1, 4, 2};
    std::sort(w.begin(), w.end());
    std::cout << "sort";
    for (int n : w) std::cout << " " << n;
    std::cout << "\n";
    return 0;
}
Terminal
-std=c++20 b_neighbors_fixed.cpp -o b_neighbors_fixed_prog
$ ./b_neighbors_fixed_prog
for_each 15
find 2 3
copy 1 5
transform 2 4 6 8 10
accumulate 15
count 1
sort 1 2 3 4 5

Read in order: for_each reports 15 - the returned summing object holds the total. find reports position 2 and the value 3 - the first element equal to 3. copy reports 1 5 - the destination's first and last elements after the range was copied into it. transform reports 2 4 6 8 10 - each element doubled into the destination. accumulate reports 15 - the same total, folded by the <numeric> neighbor. count reports 1 - one element equals 3. And sort reports 1 2 3 4 5 - the shuffled range 5, 3, 1, 4, 2 put back in order.

A ranges form since C++20, in the same header

C++20 added a ranges form of this name, and the standard declares it in the same header as the classic name. std::ranges::for_each is a function object in the ranges namespace, declared in <algorithm>, that accepts a whole range - or an iterator pair - and returns a result pairing the iterator just past the last element with the function object itself, so the accumulated state still comes back. Compiled as C++20 it answers for the same vector:

C++
#include <algorithm>
#include <iostream>
#include <vector>
struct Sum { int total = 0; void operator()(int n) { total += n; } };
int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    auto r = std::ranges::for_each(v, Sum());
    std::cout << "ranges " << r.fun.total << " " << (r.in == v.end() ? "end" : "mid") << "\n";
    return 0;
}
Terminal
-std=c++20 r_ranges.cpp -o r_ranges_prog
$ ./r_ranges_prog
ranges 15 end

The ranges line reports the total 15 and end - the function in the result holds the same accumulated state the classic call returns, and the iterator in the result stands at the end of the range. Two boundaries and one library behavior keep the forms straight. The ranges form needs C++20: compiled as C++17, that same program fails on the namespace itself, with 'std::ranges' has not been declared:

Output
-std=c++17 r_ranges_cpp17.cpp -o r_ranges_cpp17_prog
r_ranges_cpp17.cpp: In function 'int main()':
r_ranges_cpp17.cpp:7:19: error: 'std::ranges' has not been declared
    7 |     auto r = std::ranges::for_each(v, Sum());
      |                   ^~~~~~

And in this library the ranges header does not rescue the ranges form - a file whose only include is <ranges> (with <vector> for the containers) fails for it with a not-a-member error naming the ranges namespace, and a file whose only include is <array> fails for it the same way, the two transcripts identical in shape:

Output
-std=c++20 r_ranges_rangesonly.cpp -o r_ranges_rangesonly_prog
r_ranges_rangesonly.cpp: In function 'int main()':
r_ranges_rangesonly.cpp:6:27: error: 'for_each' is not a member of 'std::ranges'
    6 |     auto r = std::ranges::for_each(v, Sum());
      |                           ^~~~~~~~
Output
-std=c++20 r_ranges_arrayonly.cpp -o r_ranges_arrayonly_prog
r_ranges_arrayonly.cpp: In function 'int main()':
r_ranges_arrayonly.cpp:5:27: error: 'for_each' is not a member of 'std::ranges'
    5 |     auto r = std::ranges::for_each(v, Sum());
      |                           ^~~~~~~~

That is this library version's behavior, not the rule: the header the standard names for both forms is <algorithm>, so a complete program names it. The classic name, meanwhile, is not pulled in by the ranges header either: in the sweep probed here, a file whose only include is <ranges> fails for std::for_each with the plain error, as the sweep section above lists.

A different wording - and an argument-dependent rescue that depends on the iterators' types

Including <algorithm> is not the only half of the name. Over plain arrays, the unqualified call fails:

C++
#include <algorithm>
struct Sum { int total = 0; void operator()(int n) { total += n; } };
int main() {
    int a[5] = {1, 2, 3, 4, 5};
    Sum s = for_each(a, a + 5, Sum());
    return 0;
}
Output
-std=c++20 g_unqualified.cpp -o g_unqualified_prog
g_unqualified.cpp: In function 'int main()':
g_unqualified.cpp:5:13: error: 'for_each' was not declared in this scope
    5 |     Sum s = for_each(a, a + 5, Sum());
      |             ^~~~~~~~
g_unqualified.cpp:5:13: note: suggested alternatives:
In file included from /usr/include/c++/13/algorithm:73,
                 from g_unqualified.cpp:1:
/usr/include/c++/13/pstl/glue_algorithm_defs.h:42:1: note:   'std::for_each'
   42 | for_each(_ExecutionPolicy&& __exec, _ForwardIterator __first, _ForwardIterator __last, _Function __f);
      | ^~~~~~~~
In file included from /usr/include/c++/13/algorithm:63:
/usr/include/c++/13/bits/ranges_algo.h:205:34: note:   'std::ranges::for_each'
  205 |   inline constexpr __for_each_fn for_each{};
      |                                  ^~~~~~~~

That wording - was not declared in this scope, with notes pointing at the declarations of both std::for_each and the ranges form - is a different defect with a different fix: the header is present, the qualifier is not. Qualify the name as std::for_each; adding includes does not bring the name out of namespace std. Swap the arrays for vectors, and the same unqualified call compiles and runs:

C++
#include <algorithm>
#include <vector>
struct Sum { int total = 0; void operator()(int n) { total += n; } };
int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    Sum s = for_each(v.begin(), v.end(), Sum());
    return (s.total == 15) ? 0 : 1;
}
Terminal
-std=c++20 g_unqualified_vec.cpp -o g_unqualified_vec_prog
$ ./g_unqualified_vec_prog

That compile is argument-dependent lookup at work, not a rule to rely on: the vectors' iterators are std types, so their associated namespace is std, and lookup finds std::for_each through them. A list's iterators rescue it the same way - the same unqualified call over lists compiles and runs:

Terminal
-std=c++20 g_unqualified_list.cpp -o g_unqualified_list_prog
$ ./g_unqualified_list_prog

But the container being a std type is not enough by itself - over a std::array, the same unqualified call fails with the same wording, because in this library a std::array's iterators are plain pointers, and a pointer has no associated namespace:

C++
#include <algorithm>
#include <array>
struct Sum { int total = 0; void operator()(int n) { total += n; } };
int main() {
    std::array<int, 5> v{1, 2, 3, 4, 5};
    Sum s = for_each(v.begin(), v.end(), Sum());
    return 0;
}
Output
-std=c++20 g_unqualified_stdarray.cpp -o g_unqualified_stdarray_prog
g_unqualified_stdarray.cpp: In function 'int main()':
g_unqualified_stdarray.cpp:6:13: error: 'for_each' was not declared in this scope
    6 |     Sum s = for_each(v.begin(), v.end(), Sum());
      |             ^~~~~~~~
g_unqualified_stdarray.cpp:6:13: note: suggested alternatives:
In file included from /usr/include/c++/13/algorithm:73,
                 from g_unqualified_stdarray.cpp:1:
/usr/include/c++/13/pstl/glue_algorithm_defs.h:42:1: note:   'std::for_each'
   42 | for_each(_ExecutionPolicy&& __exec, _ForwardIterator __first, _ForwardIterator __last, _Function __f);
      | ^~~~~~~~
In file included from /usr/include/c++/13/algorithm:63:
/usr/include/c++/13/bits/ranges_algo.h:205:34: note:   'std::ranges::for_each'
  205 |   inline constexpr __for_each_fn for_each{};
      |                                  ^~~~~~~~

And with using namespace std; in the file, the qualifier question goes away by a different route - the unqualified call over vectors compiles and runs, because the using-directive brings the name into scope directly:

Terminal
-std=c++20 g_using_namespace.cpp -o g_using_namespace_prog
$ ./g_using_namespace_prog

The pattern across the probed set is exact: the rescue follows the iterator type, not the container's name - class iterators of std containers carry the name in, pointer iterators do not, whatever container stands behind them - and a using-directive bypasses the question entirely. Write the qualifier either way.

The exact rule

  • std::for_each is declared by #include <algorithm>, and by no other header by rule. In the sweep probed here, 100 of the other 105 headers in the library's header set - among them <limits>, <ranges>, <vector>, <filesystem>, and <string> - do not declare it, and neither does a file with no include at all; the remaining 5 pull it in transitively, as this library version's behavior, not as a guarantee.
  • 'for_each' is not a member of 'std' has one cause in the contexts probed here: the <algorithm> include is missing and nothing else in the file pulled the name in. It comes in one shape only in the sweep probed here: all 100 failing sole headers fail with the plain error line alone, with no suggestion tail, no note lines, and no help lines. No failing sole header produced a different error. And unlike its younger siblings, this name has no standard-based second cause: the classic call dates to C++98 and compiles with the include in place at every probed standard.
  • In the sweep probed here, 5 headers besides <algorithm> rescue std::for_each transitively - <chrono>, <execution>, <functional>, <regex>, and <valarray> - so a file whose only include is one of those compiles and runs the call without <algorithm>. That is this library version's behavior, not a guarantee - in the probed set, no header besides <algorithm> is required to pull std::for_each in.
  • The result rules are the documented ones, as the fixed programs here show: the fixed program prints result 15 for the textbook case; the semantics program prints state 0 15, order 1 2 3 4 5, mutated 2 4 6, calls 5, n-end 3, n 6, and empty 0 - the call applies the function to each element in order and returns the function object, moved in, so the accumulated state is read off the returned object, a function taking elements by reference modifies them in place, the function is applied exactly once per element, and the counted sibling std::for_each_n applies its function to the first counted elements only and returns an iterator to where it stopped.
  • The classic std::for_each dates to C++98: with <algorithm> included it compiles and runs as C++98, C++11, C++14, C++17, C++20, and C++23, each printing 15. The layered pieces have floors: std::for_each_n and the execution-policy overload start at C++17 - compiled as C++14, the counted call fails with 'for_each_n' is not a member of 'std' and the suggestion for_each, and naming the policy with only <algorithm> included fails with 'std::execution' has not been declared; with <execution> included alongside it, the policy call compiles and runs, returning nothing. Constant-expression use starts at C++20: the static-assert program here compiles as C++20 and fails as C++17.
  • The neighbors split in this library: std::find fails in a sole <vector> file with the suggestion did you mean 'std::ranges::find'? and std::count with did you mean 'popcount'?, while std::transform, std::accumulate, and std::sort fail there with the plain error, and std::copy compiles outright in that file - five of the six are declared by #include <algorithm> by rule, and std::accumulate is declared by #include <numeric> instead. The fixed neighbor program prints for_each 15, find 2 3, copy 1 5, transform 2 4 6 8 10, accumulate 15, count 1, and sort 1 2 3 4 5.
  • The ranges form of this same name is a function object in namespace std::ranges, declared in <algorithm> by the standard, needing C++20, returning a result that pairs the end iterator with the function object - compiled as C++17 the ranges program here fails with 'std::ranges' has not been declared, and compiled as C++20 it prints ranges 15 end. In the probes here <ranges> alone does not rescue it in this library - it fails with a not-a-member error naming the ranges namespace for the ranges form, <array> alone fails for it the same way, and <ranges> fails with the plain error for the classic name in the sweep.
  • 'for_each' was not declared in this scope for an unqualified for_each use is a different defect: qualify the name as std::for_each - the include alone does not bring the name out of namespace std. For this name the unqualified call's fate depends on the iterators' types: over plain arrays it fails, as the first unqualified program above shows; over a vector's iterators and over a list's iterators it is rescued through argument-dependent lookup, as the second and third show, because those iterators are std class types; over a std::array's iterators it fails again, because in this library those iterators are plain pointers; and with using namespace std; in the file it compiles outright, as the last unqualified program shows. Qualify the name either way.

The fixes, ranked

  • First, check the include list of the file that names std::for_each. If <algorithm> is not there, add it - that is the fix for the only cause of this error. It holds whether or not the file happened to compile before through one of the 5 transitive rescues and stopped compiling when its other includes changed - all 100 of the probed failures are this one cause, and every one of them is the plain line, so a missing suggestion tail is not evidence of a different problem.
  • Second, do not chase a standard upgrade for this error: this name dates to C++98, so a build set to any standard from C++98 up keeps the classic call with the include in place, and the error with the include present is never a standard problem.
  • Third, do not hunt for a suggestion to follow: this error carries none in any probed context. The names the neighboring diagnostics offer - the ranges form of find, and popcount for count - belong to other calls; a suggestion on a neighbor's error is a spelling guess, not this name's fix.
  • Fourth, do not reach for a container's header because the call reads a container, or for <iterator> because the call takes iterators. In the sweep probed here <vector>, <list>, <string>, and <iterator> all fail for this name - none of them is the declaring header by rule. The declaring header is <algorithm>, and a complete program names it alongside the container's own header.
  • Fifth, do not remove <algorithm> because a file compiles without it: in the probed set only 5 headers rescue the classic name, and those rescues are not guaranteed - a file that drops the include is one internal-include change away from the error in the first section. The same warning covers std::copy, which compiles in a sole <vector> file here by the same kind of accident.
  • Sixth, read the result off the returned object, not the object passed in: the function is moved into the call, so the passed object keeps its old state - in the semantics program the passed summing object stays at 0 while the returned one holds 15.
  • Seventh, if the error names the counted sibling instead - 'for_each_n' is not a member of 'std', with the suggestion for_each - keep <algorithm> and raise the standard to C++17: the counted call is younger than the classic one, and the suggestion names the older call, not a fix.
  • Eighth, if the error names std::execution instead - 'std::execution' has not been declared - add <execution> alongside <algorithm> and keep the standard at C++17 or later: this name does have a policy overload, and that pair of changes is the whole fix for the policy form - remembering that the policy form returns nothing, so no total can be read off it.
  • Ninth, match the standard to the one piece beyond the classic call that has a floor: constant-expression use needs C++20, and the ranges form needs C++20 - with its header still <algorithm> by the standard, not <ranges>.
  • Tenth, if the error says was not declared in this scope instead, fix the name's qualifier to std::for_each as well - and do not rely on argument-dependent lookup to rescue the unqualified call, because a plain array and a std::array each remove that rescue in the probed set.

Sources

  • cppreference, std::for_each - the function templates are defined in <algorithm>; std::for_each applies the given function object to each element of the range in order and returns the function object, the execution-policy overload is marked since C++17 and the classic overload constexpr since C++20, and the complexity is exactly the length of the range in applications of the function.
  • cppreference, std::for_each_n - the counted sibling, also defined in <algorithm>, marked since C++17 and constexpr since C++20, which applies the function object to the first counted elements of a sequence and returns an iterator just past the last element it applied to.
  • cppreference, <algorithm> header - the header that declares this name and the other algorithm names used as neighbors here.
  • cppreference, std::ranges::for_each - the C++20 ranges form of this name, a function object in namespace std::ranges declared in <algorithm>, returning a result that pairs the end iterator with the function object.

Keep Exploring