Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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

like image 306
Mircea Ispas Avatar asked Aug 30 '11 19:08

Mircea Ispas


People also ask

Is Vector a template in C++?

vector is a template class, which can be instantiated with a type, in the format: vector<int> , vector<double> , vector<string> . The same template class can be used to handle many types, instead of repeatably writing codes for each of the type.

Is STD A vector template?

Vectors, or std::vector , are a template class in the STL (Standard Template Library). But what does that mean? They are a more flexible, refined, and efficient replacement for arrays, which are used in the C programming language (and on which the C++ language is based).

What is template argument in C++?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

How do you declare a template function in C++?

To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>( float original ); Template arguments may be omitted when the compiler can infer them.


2 Answers

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 e.g. 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.

like image 53
Cat Plus Plus Avatar answered Nov 11 '22 02:11

Cat Plus Plus


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;
    }
}
like image 30
Seth Carnegie Avatar answered Nov 11 '22 01:11

Seth Carnegie