Template in template - access to contained type from template type

I tried to write a quicksort boilerplate function. The thought in my head was that I would write a quicksort that can work with any data structure that has an index operator and an order relation to the objects contained in it, so I could do things like

quicksort<deque<int> >();
quicksort<vector<string> >(); 

and etc.

I started with a feature like

template<typename T>
void quicksort(T& list);

The problem that I immediately ran into came with a function that performs the swap operation, which is necessary for sorting. I need to know if the values ​​that I am replacing are strings, characters, ints, regardless of what I can make temporary for the exchange!

- ( , , , ):

template<typename T, typename R>
void quicksort(T<R>& list);

, T, . , , T , , , .

? , . ?

+3
3

typedef value_type, T:

template <typename ContainerT>
void quicksort(ContainerT& container)
{
    typedef typename ContainerT::value_type ElementT;
    // etc.
}

, , , . ,

template <typename RandomAccessItT>
void quicksort(RandomAccessItT first, RandomAccessItT last)
{
    typedef std::iterator_traits<RandomAccessItT>::value_type ElementT;
    // etc.
}
+3

T STL, :

typename T::value_type

, , T std::vector<std::string>, typename T::value_type std::string.

+2

You can use std :: swap to replace two values.

Your template function should look something like this:

template < class ContainterType >
void quicksort( ContainerType &container )
{
 //  ...
}
+1
source

Source: https://habr.com/ru/post/1772203/


All Articles