Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enhanced FOR loops in C++

Tags:

java

c++

for-loop

I am switching from Java to C++ and I was wondering whether C++ contains the enhanced for loops that I used in java, in example:

int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) {   System.out.println("Count is: " + item); } 

Is this same "shortcut" possible in C++?

like image 253
Daniel Gratzer Avatar asked Dec 04 '11 21:12

Daniel Gratzer


People also ask

What is an enhanced for loop?

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.

Does C++ have an enhanced for loop?

Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.


2 Answers

C++11 does. They are called range-based fors. Remember that you should qualify the type as a reference or a reference to const.

The workaround for C++03 is BOOST_FOR_EACH or boost::bind in combination with std::for_each. More fancy things are possible with Boost.Lambda. Should you be in the mood to frustrate either yourself or your co-workers I recommend the deprecated binders std::bind1st and std::bind2nd.

Here is some example code:

#include <iostream> #include <vector> #include <algorithm> #include <iterator> #include <boost/lambda/lambda.hpp> #include <functional>      int main() {   int i = 0;   std::vector<int> v;   std::generate_n(std::back_inserter(v), 10, [&]() {return i++;});    // range-based for   // keep it simple   for(auto a : v)     std::cout << a << " ";   std::cout << std::endl;    // lambda   // i don't like loops   std::for_each(v.begin(), v.end(), [](int x) {        std::cout << x << " ";     });   std::cout << std::endl;    // hardcore   // i know my lib   std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));   std::cout << std::endl;     // boost lambda   // this is what google came up with   // using for the placeholder, otherwise this looks weird   using namespace boost::lambda;   std::for_each(v.begin(), v.end(), std::cout << _1 << " ");   std::cout << std::endl;    // fold   // i want to be a haskell programmer   std::accumulate(v.begin(), v.end(), std::ref(std::cout),                    [](std::ostream& o, int i) -> std::ostream& { return o << i << " "; });    return 0; } 
like image 88
pmr Avatar answered Sep 20 '22 11:09

pmr


In C++11, if your compiler supports it, yes it is. It's called range-based for.

std::vector<int> v;  // fill vector  for (const int& i : v) { std::cout << i << "\n"; } 

It works for C style arrays and any type that has functions begin() and end() that return iterators. Example:

class test {     int* array;     size_t size; public:     test(size_t n) : array(new int[n]), size(n)     {         for (int i = 0; i < n; i++) { array[i] = i; }     }     ~test() { delete [] array; }     int* begin() { return array; }     int* end() { return array + size; } };  int main() {     test T(10);     for (auto& i : T) {         std::cout << i;   // prints 0123456789     } } 
like image 35
jrok Avatar answered Sep 19 '22 11:09

jrok