Function templates for arbitrary STL containers containing arbitrary types

I have an arbitrary STL container C that contains elements of an arbitrary type T. I want to create a std :: vector that has a copy of all the elements. What is the cleanest way to do this?

template <typename C>
void myfunction(C container){

     /*Derive the type T of elements within the container*/

     std::vector<T> mystack;

    /* Iterate over container and push_back() the elements into mystack*/
} 
+5
source share
2 answers

STL structures, such as vectorand set, must contain a type value_typethat is typedef-ed before T.

std::vector<typename C::value_type> mystack;

By the way, you do not need to sort the container yourself. Just use

template <typename C>
void myfunction(const C& container){
  std::vector<typename C::value_type> mystack(container.begin(), container.end());
  ...
}
+11
source

. , ++ ... . iterator_traits :

template <typename It>
void myfunction(It start, It end) {
    // Get value for iterator:

    typedef typename std::iterator_traits<It>::value_type T;

    // Do something, e.g. calculate the minimum:

    T min_value = *std::min_element(start, end);
}

, typename typedef, value_type , .. , ++ , ( , , ) .

+10

All Articles