Pergunta

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();
}
Foi útil?

Solução

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.

Outras dicas

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.

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>);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top