priority_queue sample (C++)

user-defined class에 대한 STL의 priority_queue 사용 예제

class Node
{
public :
        Node( int x, int y, int cost = 0 )
           : x(x), y(y), cost(cost) {}
        Node( const Node & rhs )
           : x( rhs.x ), y ( rhs.y ), cost( rhs.cost ) {}

        Node & operator = ( const Node & rhs )
        {
                x = rhs.x;
                y = rhs.y;
                cost = rhs.cost;
                return *this;
        }
        
        void setCost( int c ) { cost = c; }

        bool operator < ( const Node & rhs ) const
        {
                return cost < rhs.cost;
        }

        bool operator > ( const Node & rhs ) const
        {
                return cost > rhs.cost;
        }

        void print() const
        {
                cout << x << " " << y << " " << cost << endl;
        }

private :
        int x;
        int y;
        int cost;
};

////// ........
#include <queue>

using namespace std;

///.........
    priority_queue<Node, vector<Node>, greater<Node> > pq;

    pq.push( Node( 1, 1, 10 ) );
    pq.push( Node( 1, 4, 7 ) );
    pq.push( Node( 1, 3, 15 ) );
    pq.push( Node( 1, 7, 0 ) );
    pq.push( Node( 1, 2, 7 ) );

    while ( ! pq.empty() )
    {
        pq.top().print();
        pq.pop();
    }


결과 (비용이 적은 순으로 출력)
1 7 0
1 4 7
1 2 7
1 1 10
1 3 15

by 오자 | 2008/07/03 01:10 | 플밍놀이 | 트랙백 | 덧글(4)

트랙백 주소 : http://palabras.egloos.com/tb/4462956
☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]
Commented by deisys at 2008/07/03 07:20
전 모종의 이유로, priority_queue 대신 set 을 쓰는 경우가 훨씬 많아요 ;-)
Commented by 오자 at 2008/07/10 01:27
priority_queue 대신 set을 쓰는 건 삽입되는 요소의 중복성을 알아서(?) 제거하려는 의도인건가요?
Commented by 오자 at 2008/07/10 01:27
GPG에 STL에 대한 재밌는 토론(?)이 올라왔네요.

http://gpgstudy.com/forum/viewtopic.php?t=20265

알짜배기 글들이 좀 있어서 나중에 추려 봐야할듯..
Commented by deisys at 2008/07/14 10:19
중복보다는 순서(?) 가 다르거든요. ㅎㅎㅎ

:         :

:

비공개 덧글

◀ 이전 페이지          다음 페이지 ▶