The simplest foreach implementation (VC & GCC)

Source: Internet
Author: User
Tags foreach vc9

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.