views:

124

answers:

2

hi

how can I use for each loop in GCC?

and how can i get GCC version? (in code)

+5  A: 

Use a lambda, e.g.

// C++0x only.
std::for_each(theContainer.begin(), theContainer.end(), [](someType x) {
    // do stuff with x.
});

The range-based for loop is not supported by GCC as of version 4.6.

// C++0x only, not widely supported
for (auto x : theContainer) {
   // do stuff with x.
}

The "for each" loop syntax is an MSVC extension. It is not available in other compilers.

// MSVC only
for each (auto x in theContainer) {
  // do stuff with x.
}

But you could just use Boost.Foreach. It is portable and available without C++0x too.

// Requires Boost
BOOST_FOREACH(someType x, theContainer) {
  // do stuff with x.
}

See How do I test the current version of GCC ? on how to get the GCC version.

KennyTM
no,in C++0x format. like as VC++ 2010:for each( auto it in vec){cout << it << endl;}
@user: `for each` is not C++0x.
KennyTM
Is `for each` C++cli, or is it an extension to raw C++?
Johannes Schaub - litb
@Johannes std::for_each(,,) is currently part of the ISO Standard C++, defined in 2003. It is not an extension, it is part of the currently available features in C++. One has to include the `<algorithm>` header.
Stephane Rolland
+2  A: 

there is also the traditionnal way, not using C++0X lambda. The <algorithm> header is designed to be used with objects that have a defined operator parenthesis. ( C++0x lambdas are only of subset of objects that have the operator () )

struct Functor
{
   void operator()(MyType& object)
   {
      // what you want to do on objects
   }
}

void Foo(std::vector<MyType>& vector)
{
  Functor functor;
  std::for_each(vector.begin(), vector.end(), functor);
}

see alogrithm header reference for a list of all c++ standard functions that work with functors and lambdas.

Stephane Rolland