对于GCC和GCC版本中的每一个

use*_*870 4 c++ foreach gcc c++11

如何在GCC中使用每个循环?

我怎样才能获得GCC版本?(在代码中)

ken*_*ytm 24

使用lambda,例如

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

范围为基础的循环是通过GCC自4.6支持.

// C++0x only
for (auto x : theContainer) {
   // do stuff with x.
}
Run Code Online (Sandbox Code Playgroud)

"每个"循环语法是MSVC扩展.它在其他编译器中不可用.

// MSVC only
for each (auto x in theContainer) {
  // do stuff with x.
}
Run Code Online (Sandbox Code Playgroud)

但你可以使用Boost.Foreach.它是可移植的,也可以没有C++ 0x.

// Requires Boost
BOOST_FOREACH(someType x, theContainer) {
  // do stuff with x.
}
Run Code Online (Sandbox Code Playgroud)

请参阅如何测试当前版本的GCC?关于如何获得GCC版本.


Ste*_*and 6

还有传统的方式,不使用C++ 0X lambda.的<algorithm>报头被设计成与具有定义的运算符的括号的对象一起使用.(C++ 0x lambdas只是具有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);
}
Run Code Online (Sandbox Code Playgroud)

请参阅算法标题参考,以获取与仿函数和lambda一起使用的所有c ++标准函数的列表.