By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,413 Members | 1,023 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,413 IT Pros & Developers. It's quick & easy.

foreach shorthand

P: n/a
I want to write a shorthand version of the following code, which
iterates over all the elements of a STL container, e.g. vector:

for (vector<char>::const_iterator i = v.begin(); i != v.end(); ++i)
{
...
}

I want to reduce this somewhat bulky line, which appears everywhere in
my code, to something shorter, like:

for_each_i(v)
{
....
}

I'm not using the STL for_each because I don't necessarily want to
define a function/functor for my for loop.

It seems the problem is I can't get v's type from v. No "typeof" in
C++.
So I have to settle with something that looks like this:
for_each_i(vector<char>, v)
{
...
}
... which is ugly.

Any ideas on how to implement this for_each_i macro?

Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
un*********@gmail.com wrote:
I want to write a shorthand version of the following code, which
iterates over all the elements of a STL container, e.g. vector: I want to reduce this somewhat bulky line, which appears everywhere in
my code, to something shorter, like:

for_each_i(v)
{
...
} Any ideas on how to implement this for_each_i macro?


See http://www.artima.com/cppsource/foreach.html

Jonathan
Jul 23 '05 #2

P: n/a
un*********@gmail.com wrote:
I'm not using the STL for_each because I don't necessarily want to
define a function/functor for my for loop.


If the loop body is small, you might be able to use Boost's lambda library:

http://boost.org/doc/html/lambda.html

An example usage from that page:

for_each(a.begin(), a.end(), std::cout << _1 << ' ');

On the other hand; if the loop body is large, moving the logic to a
function/functor would be a good idea.

Ali

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.