Answer the question
In order to leave comments, you need to log in
Using decltype or...?
I was reading about the STL over the weekend and a few thoughts came to mind.
Suppose you are writing a class for sorting with a single function of the same name. Let's also say that you want to do something similar to the STL. We look at the description of sort in STL.
template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
template <class T> struct less {
bool operator() (const T& x, const T& y) const {return x<y;}
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};
std::less<тип> comp;
sort (first, last, comp);
sort( first, last, std::less< decltype(*first) >() );
#include <algorithm> // std::swap
class BubbleSort
{
public:
template< class RandomAccessIterator >
static void sort( RandomAccessIterator first, RandomAccessIterator last )
{
sort( first, last, std::less< decltype(*first) >() );
}
template< class RandomAccessIterator, class Compare >
static void sort( RandomAccessIterator first, RandomAccessIterator last, Compare comp )
{
for( auto i = first; i != last; i++ )
{
for( auto j = i + 1; j != last; j++ )
{
if( comp( *j, *i ) )
std::swap( *i, *j );
}
}
}
private:
BubbleSort(void);
~BubbleSort(void);
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question