Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-09-12 09:22:42


From: "Mark Snelling" <mark_at_[hidden]>
> Hello,
> I need some help using the boost::bind library. I have a map of objects
> with a string as the key eg map<string, Block*>, what I want to do is
> call a member function on each Block* in the map using the std::for_each
> algorithm. The trivial solution would be to craft my own loop and
> iterate through the list calling the member function on each one. But
> I'm sure that the boost::bind library can help me out there.
>
> class Block
> {
> public:
> void update(int x);
> };
>
> void main()
> {
> map<string, Block*> blocks;
> for_each(blocks.begin(), blocks.end(), *****);
> }
>
> what should I replace the ***** with to call update() on each block?

    std::for_each(blocks.begin(), blocks.end(),
        boost::bind(&Block::update,
            boost::bind(&std::map<std::string, Block*>::value_type::second,
_1),
            5
        )
    );

if you insist. :-)

Another option:

template<class It, class F> void for_each_pair(It first, It last, F f)
{
    for(; first != last; ++first)
    {
        f(first->first, first->second);
    }
}

int main()
{
    std::map<std::string, Block*> blocks;
    for_each_pair(blocks.begin(), blocks.end(), boost::bind(&Block::update,
_2, 5));
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net