> Is set like to priority_queue according to algorithm?I need a heap algorithm.
no.
> removing the first is so easy.
> removing ...is difficult. Because priority_queue hasnt a remove function.
the simplest solution may be to write your own priority_queue which has an erase function. (it will not be a priority_queue in a strict sense, but a heap with erase functionality).
#include <vector>
#include <algorithm>
#include <iterator>
template< typename T, typename sequence_type = std::vector<T>,
typename cmp_function_t =
std::less< typename sequence_type::value_type > >
struct my_priority_queue
{
// *** note: ignoring c++0x concepts requirements ***
// 1. T has AssignableConcept
// 2. sequence_type has SequenceConcept
// 3. sequence_type has RandomAccessContainerConcept
// 4. T and sequence_type::value_type have SameTypeConcept
// 5. cmp_function_t has bool(T,T) BinaryFunctionConcept
typedef typename sequence_type::value_type value_type;
typedef typename sequence_type::reference reference;
typedef typename sequence_type::const_reference const_reference;
typedef typename sequence_type::size_type size_type;
typedef sequence_type container_type;
explicit my_priority_queue(
const cmp_function_t& fn = cmp_function_t(),
const sequence_type& cntr = sequence_type() )
: c( cntr ), comp( fn )
{ std::make_heap( c.begin(), c.end(), comp ) ; }
template<typename iterator_t>
my_priority_queue( iterator_t begin, iterator_t end,
const cmp_function_t& fn = cmp_function_t(),
const sequence_type& cntr = sequence_type() )
: c( cntr ), comp( fn )
{
c.insert( c.end(), begin, end ) ;
std::make_heap( c.begin(), c.end(), comp ) ;
}
bool empty() const { return c.empty() ; }
size_type size() const { return c.size() ; }
const_reference top() const { return c.front(); }
void push( const value_type& v )
{
c.push_back(v);
std::push_heap( c.begin(), c.end(), comp ) ;
}
void pop()
{
std::pop_heap( c.begin(), c.end(), comp ) ;
c.pop_back();
}
void erase( const value_type& v )
{
typedef typename sequence_type::iterator iterator ;
iterator where = std::find( c.begin(), c.end(), v ) ;
if( where != c.end() )
{
c.erase( where ) ;
std::make_heap( c.begin(), c.end(), comp ) ;
}
}
protected:
sequence_type c ;
cmp_function_t comp ;
} ;
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287