loop -> for_each

Discussion in 'C++' started by ibe, Jan 13, 2006.

  1. ibe

    ibe Guest

    Hi,
    i can't get the clue:
    I hav a loop in my code like this:

    ---snip---

    class Foo {
    accept(Visitor& v) {
    v.visit(*this);
    }
    };

    class Visitor {
    visit (Foo& f) {
    ...
    }
    }

    ....in main...

    Visitor v(arugments, ...);
    for (std::deque<Foo*>::iterator iter = list_.begin();
    iter != m_list.end();
    ++iter) {
    (*iter)->accept(v);
    }

    ---snip---

    Now i would like to do this with for_each. I think i need std::mem_fun (or
    bind1st ?!?).
    Can anyone help me?

    htx
    ibe
     
    ibe, Jan 13, 2006
    #1
    1. Advertising

  2. ibe

    Thomas Jakob Guest

    ibe wrote:
    > Hi,
    > i can't get the clue:
    > I hav a loop in my code like this:
    >
    > ---snip---
    >
    > class Foo {
    > accept(Visitor& v) {
    > v.visit(*this);
    > }
    > };
    >
    > class Visitor {
    > visit (Foo& f) {
    > ...
    > }
    > }
    >


    I changed this in my example to:

    struct Foo;

    struct Visitor {
    void visit (Foo& f) {
    }
    };

    struct Foo {
    void accept(Visitor* v) {
    v->visit(*this);
    }
    };

    Using a reference in Foo::accept will cause a "reference to reference",
    if u want to use a reference boost::ref might be a solution.


    > ....in main...
    >
    > Visitor v(arugments, ...);
    > for (std::deque<Foo*>::iterator iter = list_.begin();
    > iter != m_list.end();
    > ++iter) {
    > (*iter)->accept(v);
    > }
    >
    > ---snip---
    >
    > Now i would like to do this with for_each. I think i need std::mem_fun (or
    > bind1st ?!?).
    > Can anyone help me?
    >
    > htx
    > ibe


    Try

    std::for_each(list.begin(), list.end(),
    std::bind2nd(std::mem_fun(&Foo::accept), &v));

    But i would always prefer boost::bind.


    --
    Greetings, Thomas Jakob
    quicix (at) gmail (dot) com
     
    Thomas Jakob, Jan 13, 2006
    #2
    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. ibe

    loop -> for_each

    ibe, Jan 20, 2006, in forum: C++
    Replies:
    0
    Views:
    341
  2. ibe
    Replies:
    5
    Views:
    387
    Luke Meyers
    Jan 20, 2006
  3. Sarath
    Replies:
    13
    Views:
    720
    V.R. Marinov
    Jun 5, 2007
  4. Skirmish
    Replies:
    9
    Views:
    983
    James Kanze
    Jul 24, 2007
  5. Isaac Won
    Replies:
    9
    Views:
    387
    Ulrich Eckhardt
    Mar 4, 2013
Loading...

Share This Page