14
#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.

2
  • 5
    It 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. Commented Jun 24, 2013 at 2:25
  • stackoverflow.com/q/15027282/62576 Commented Jun 24, 2013 at 2:27

2 Answers 2

16

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).

Sign up to request clarification or add additional context in comments.

Comments

4

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);

1 Comment

std::for_each is still defined in the algorithm header, even in C++11. (The range-based for-loop introduced by C++11 into the language core has not replaced the std::for_each algorithm, even though there is some overlap in the use cases.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.