Boost logo

Boost Users :

From: Mark Snelling (mark_at_[hidden])
Date: 2002-09-12 11:19:40


Thanks for the help. I have another question though on a similar topic...

Say I have a function:

void deleter(B* b)
{
     delete b;
}

and a list:

std::list<Object*> mylist;

I can call the for_each algorithm on this list using my function above:

std::for_each(mylist.begin(), mylist.end(), &deleter);

and it will delete all of the objects pointed to in the list.
Is it possible to convert deleter into a templated function:

template<class T> void deleter(T* t)
{
    delete t;
}

and pass that into the for_each algorithm?

If so, How?

Mark.

Peter Dimov wrote:
> 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));
> }
>
>
>
> Info: <http://www.boost.org>
> Wiki: <http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl>
> Unsubscribe: <mailto:boost-users-unsubscribe_at_[hidden]>
>
>
> Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
>
>


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