foreach is said to have entered the new C + + standard, but it is easy to write one yourself before the compiler supports it.
(1) foreach Standard usage:
std::vector<int> vec;
foreach(int i, vec){
std::cout << i;
}
(2) VC implementation
In the latest VC version of the original has been similar to the support of foreach, change the name on the line:
#define foreach(var, container)for each(var in containter)
(3) GCC implementation
GCC does not have inline support, but it is not too difficult to implement because GCC supports typeof keywords. (There is a bug that has been corrected under Ownwaterloo reminders)
template <typename C> struct foreach_helper {
typename C::const_iterator it, end;
foreach_helper (const C& c): it(c.begin()), end(c.end()){}
};
#define RANDOM_VAR(name, line)RANDOM_VAR_(name, line)
#define RANDOM_VAR_(name, line)name ## line
#define foreach(var, container) \
__typeof__(container)const& RANDOM_VAR(_con_, __LINE__)= container;\
for (foreach_helper <__typeof__(container)> _fh_(RANDOM_VAR(_con_, __LINE__)); _fh_.it != _fh_.end; ++_fh_.it)\
for (var = *_fh_.it;; __extension__ ({break;}))
A special consideration here is that container may be a temporary object, or a return value of a function. In order to not replicate the container, a less-known C + + feature is used, that is, when a reference is present in a temporary variable, the lifetime is determined by the reference variable. This ensures that the loop is always valid.
(4) Performance
I tested each with GCC and VC9 (the optimization option uses O2), and the results showed that there was almost no difference between using foreach and ordinary iterator traversal. However, GCC's traversal performance is significantly better than VC9 (with a Chinese-style conclusion that is about five times times better), my test is of course very sketchy, not worth believing.