foreach shorthand

G

Guest

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?
 
?

=?iso-8859-1?Q?Ali_=C7ehreli?=

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,905
Latest member
Kristy_Poole

Latest Threads

Top