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();
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With