简体   繁体   中英

C++ template function that receives std::vector as argument

I need to make a template function that receives as parameter a std::container of some type - let's say std::vector and deletes all elements from that container. I need a function equivalent to this:

for_each(some_vector.begin(), some_vector.end(), [](some_vector_type* element){delete element;}); 

The call should be something like:

delete_all_elements(some_vector);

Is this possible?

EDIT: I want to use first code inside delete_all_elements

Why wouldn't it be?

template <typename C>
void delete_all_elements(C& container) {
    std::for_each(
        container.begin(), container.end(),
        [](typename C::value_type ptr) { delete ptr; }
    );
    container.clear();
}

You can add eg static_assert(std::is_pointer<typename C::value_type>::value, "Elements must be pointers"); at the beginning to ensure you won't try to delete non-pointers.

Why not do something like virtually every STL algorithm:

template<typename Iterator>
void delete_all_elements(Iterator begin, Iterator end) {
    while (begin != end) {
        delete *begin;
        ++begin;
    }
}

The canonical way is:

template <typename I>
void delete_all_elements(I begin, I end)
{
    for (; begin != end; ++begin) delete *begin;
}

Are you looking for this (C++03 solution):

template<typename Container>
void delete_all(const Container & c)
{
   typename Container::const_iterator begin = c.begin(), end = c.end();
   while ( begin != end ) { delete *begin; ++begin; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM