views:

273

answers:

3

I'm trying to get a simple delete every pointer in my vector/list/... function written with an ultra cool lambda function. Mind you, I don't know c**p about those things :)

template <typename T>
void delete_clear(T const& cont)
{
    for_each(T.begin(), T.end(), [](???){ ???->delete() } );
}

I have no clue what to fill in for the ???'s. Any help is greatly appreciated!

UPDATE: This is what it should look like:

template <typename Container>
void delete_clear(Container &c)
{
    for_each(c.begin(), c.end(), [](typename Container::value_type x){ delete x; } );
    c.clear();
}
+3  A: 

How about something like:

template <typename Container>
void delete_all(const Container& c)
{
    typedef typename Container::value_type Value;
    std::for_each(c.begin(), c.end(), [](const Value& v){ delete v; });
}

Note that this doesn't remove the pointers from the container, so you need to be very careful what you do with the container and the pointers it contains after you call this.

James McNellis
Thanks for catching the missing T.clear()
rubenvb
+7  A: 

Two issues here: the lambda syntax itself, and how to get the value type of a container:

To call the mydelete() function on each pointer (assuming you've defined a mydelete() member function):

for_each(c.begin(), c.end(), [](typename T::value_type x){ x->mydelete(); } );

To delete them using the delete operator:

for_each(c.begin(), c.end(), [](typename T::value_type x){ delete x; } );

I'd note that it's a bit dodgy to take a const reference to a container, and delete everything in it, although the language doesn't stop you because of what pointers are. Are you sure that's a "constant" operation, though, within the meaning and use of your container?

If you're writing this code, maybe you'd benefit from Boost pointer containers, or containers of shared_ptr.

Steve Jessop
Two good answers, but this one I like better (operator<->member function delete + one line). Thanks
rubenvb
Except that delete is a keyword and thus can't be the name of anything.
Noah Roberts
@Noah: Good point, well made.
Steve Jessop
Looks like this (and the question update) mixes type T with a value of type T.
Potatoswatter
Oh yes, I c'n'p'ed the line.
Steve Jessop
@Steve: thanks, my bad :s
rubenvb
A: 

Are you interested specifically in lambdas?

If you're using boost you can write:

for_each(c.begin(), c.end(), boost::checked_delete<Container::value_type>);
utnapistim