foreach shorthand

Discussion in 'C++' started by unspammable@gmail.com, Mar 25, 2005.

  1. 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?
     
    , Mar 25, 2005
    #1
    1. Advertising

  2. 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
     
    Jonathan Turkanis, Mar 25, 2005
    #2
    1. Advertising

  3. 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
     
    =?iso-8859-1?Q?Ali_=C7ehreli?=, Mar 25, 2005
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. David W
    Replies:
    0
    Views:
    917
    David W
    Jan 17, 2007
  2. Foxpointe

    Shorthand for namespaces

    Foxpointe, Oct 31, 2006, in forum: XML
    Replies:
    4
    Views:
    445
    Foxpointe
    Oct 31, 2006
  3. Replies:
    7
    Views:
    410
  4. Tilman  Kispersky
    Replies:
    2
    Views:
    380
    Paul Hankin
    Jun 8, 2008
  5. asit
    Replies:
    4
    Views:
    3,620
    Roedy Green
    Jul 3, 2008
Loading...

Share This Page