【问题标题】:for each in GCC and GCC version对于 GCC 和 GCC 版本中的每个
【发布时间】:2011-04-02 00:40:16
【问题描述】:

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

我如何获得 GCC 版本? (在代码中)

【问题讨论】:

  • 我看不出这两个问题有什么关系...

标签: c++ gcc foreach c++11


【解决方案1】:

使用 lambda,例如

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

GCC 从 4.6 开始支持 range-based for loop

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

"for each" loop 语法是 MSVC 扩展。它在其他编译器中不可用。

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

但你可以只使用Boost.Foreach。它是可移植的,也可以在没有 C++0x 的情况下使用。

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

请参阅How do I test the current version of GCC ?,了解如何获取 GCC 版本。

【讨论】:

  • 否,采用 C++0x 格式。就像 VC++ 2010 一样:for each(auto it in vec) { cout
  • @user: for each 不是 C++0x。
  • for each C++cli,还是原始C++的扩展?
  • @Johannes std::for_each(,,) 目前是 2003 年定义的 ISO 标准 C++ 的一部分。它不是扩展,它是 C++ 中当前可用功能的一部分。必须包含 <algorithm> 标头。
  • GCC 4.6 是 releasedrange-based for
【解决方案2】:

还有一种传统方式,不使用 C++0X lambda。 <algorithm> 标头旨在与具有已定义运算符括号的对象一起使用。 (C++0x lambda 只是具有运算符 () 的对象的子集)

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

请参阅 algorithm header reference 以获取所有使用仿函数和 lambda 的 C++ 标准函数的列表。

【讨论】:

    猜你喜欢
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 2012-03-29
    • 1970-01-01
    • 2018-01-12
    • 2012-06-25
    相关资源
    最近更新 更多