【发布时间】:2011-04-02 00:40:16
【问题描述】:
如何在 GCC 中使用每个循环?
我如何获得 GCC 版本? (在代码中)
【问题讨论】:
-
我看不出这两个问题有什么关系...
如何在 GCC 中使用每个循环?
我如何获得 GCC 版本? (在代码中)
【问题讨论】:
使用 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 版本。
【讨论】:
for each 不是 C++0x。
for each C++cli,还是原始C++的扩展?
<algorithm> 标头。
还有一种传统方式,不使用 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++ 标准函数的列表。
【讨论】: