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.

Ra1nWarden
  • 1,170
  • 4
  • 21
  • 37

2 Answers2

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

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
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);

Hut8
  • 6,080
  • 4
  • 42
  • 59
  • 4
    `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.) – jogojapan Jun 24 '13 at 02:33