How to use for each loop in c++

51,906

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

Share:
51,906

Related videos on Youtube

Ra1nWarden
Author by

Ra1nWarden

Updated on July 22, 2022

Comments

  • Ra1nWarden
    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
      jogojapan over 10 years
      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.
  • jogojapan
    jogojapan over 10 years
    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.)

Related