how can I use for each loop in GCC?
如何在GCC中使用每个循环?
and how can i get GCC version? (in code)
我怎样才能获得GCC版本? (在代码中)
2 个解决方案
#1
22
Use a lambda, e.g.
使用lambda,例如
// C++0x only.
std::for_each(theContainer.begin(), theContainer.end(), [](someType x) {
// do stuff with x.
});
The range-based for loop is supported by GCC since 4.6.
自4.6以来,GCC支持基于范围的for循环。
// C++0x only
for (auto x : theContainer) {
// do stuff with x.
}
The "for each" loop syntax is an MSVC extension. It is not available in other compilers.
“for each”循环语法是MSVC扩展。它在其他编译器中不可用。
// 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.
但你可以使用Boost.Foreach。它是可移植的,也可以没有C ++ 0x。
// 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.
请参阅如何测试当前版本的GCC?关于如何获得GCC版本。
#2
6
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 () )
还有传统方式,不使用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);
}
see algorithm header reference for a list of all c++ standard functions that work with functors and lambdas.
请参阅算法标题参考,以获取与仿函数和lambda一起使用的所有c ++标准函数的列表。
#1
22
Use a lambda, e.g.
使用lambda,例如
// C++0x only.
std::for_each(theContainer.begin(), theContainer.end(), [](someType x) {
// do stuff with x.
});
The range-based for loop is supported by GCC since 4.6.
自4.6以来,GCC支持基于范围的for循环。
// C++0x only
for (auto x : theContainer) {
// do stuff with x.
}
The "for each" loop syntax is an MSVC extension. It is not available in other compilers.
“for each”循环语法是MSVC扩展。它在其他编译器中不可用。
// 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.
但你可以使用Boost.Foreach。它是可移植的,也可以没有C ++ 0x。
// 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.
请参阅如何测试当前版本的GCC?关于如何获得GCC版本。
#2
6
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 () )
还有传统方式,不使用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);
}
see algorithm header reference for a list of all c++ standard functions that work with functors and lambdas.
请参阅算法标题参考,以获取与仿函数和lambda一起使用的所有c ++标准函数的列表。