1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <functional>
#include <queue>
#include <initializer_list>
#include <iostream>
template< typename T, typename CMP = std::less<T> > struct pq_over_q
{
explicit pq_over_q( CMP c = CMP() ) : cmp(c) {}
template < typename ITERATOR > pq_over_q( ITERATOR begin, ITERATOR end )
{ for( ; begin != end ; ++begin ) push(*begin) ; }
template < typename U > pq_over_q( std::initializer_list<U> ilist )
{ for( auto iter = ilist.begin() ; iter != ilist.end() ; ++iter ) push(*iter) ; }
void push( const T& v )
{
q.push(v) ;
bring_top_to_front() ;
}
T& top() { return q.front() ; }
const T& top() const { return q.front() ; }
void pop() { q.pop() ; bring_top_to_front() ; }
bool empty() const { return q.empty() ; }
std::size_t size() const { return q.size() ; }
private:
std::queue<T> q ;
CMP cmp ;
void bring_top_to_front()
{
if( !q.empty() )
{
T top( find_top() ) ;
while( cmp( q.front(), top ) ) rotate() ;
}
}
T find_top()
{
T top( q.front() ) ;
for( std::size_t i = 1 ; i < q.size() ; ++i )
{
rotate() ;
if( cmp( top, q.front() ) ) top = q.front() ;
}
return top ;
}
void rotate() { if( q.size() > 1U ) q.push( q.front() ) ; q.pop() ; }
};
int main()
{
pq_over_q< int, std::greater<int> > pq = { 1, 2, 7, 4, 9, 2, 5, 4, 5, 4, 7, 6 } ;
while( !pq.empty() ) { std::cout << pq.top() << ' ' ; pq.pop() ; }
}
|