How to use for each loop in c++
Solution 1
The code is valid, as can be demonstrated on an online compiler.
Please refer to your compiler documentation to be sure you have enabled C++11. The option is often called -std=c++11
. You might have to download an upgrade; check your package manager for GCC (currently at 4.8) or Clang (currently 3.3).
Solution 2
Prior to C++11x, for_each
is defined in the algorithm
header.
Simply use:
for_each (vec.begin(), vec.end(), fn);
where fn
is a function to which the element will be passed, and the first two arguments are input iterators.
Also, after including both string
and algorithm
you could just use
std::transform(str.begin(), str.end(),str.begin(), ::toupper);
Related videos on Youtube

Ra1nWarden
Updated on July 22, 2022Comments
-
Ra1nWarden over 1 year
#include <cstdlib> #include <iostream> #include <string> using namespace std; int main() { string str("hello world!"); for (auto &c : str) c = toupper(c); cout << str; return 0; }
This c++ code does not compile. Error msg: main.cpp:21: error: a function-definition is not allowed here before ':' token Question: Is there a for each loop in c++ (range for loop?)? what is wrong with the for each loop above?
Thanks in advance.
-
jogojapan over 10 yearsIt exists in C++11. Make sure you use a compiler that can handle C++11, and make sure you enable the required options for that.
-
-
jogojapan over 10 years
std::for_each
is still defined in thealgorithm
header, even in C++11. (The range-based for-loop introduced by C++11 into the language core has not replaced thestd::for_each
algorithm, even though there is some overlap in the use cases.)