Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda+for_each+delete on STL containers

I'm trying to get a simple delete every pointer in my vector/list/... function written with an ultra cool lambda function.

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();
}
like image 831
rubenvb Avatar asked May 19 '10 20:05

rubenvb


1 Answers

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; } );

Also, lambda isn't necessarily the coolest new feature in C++11 for a given problem:

for(auto x : c) { 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.

like image 73
Steve Jessop Avatar answered Oct 15 '22 18:10

Steve Jessop