Блог пользователя ghost016

Автор ghost016, 13 лет назад, По-английски
Hi...

I am facing problem while operator overloading in the priority queue... my following code snippet return wrong..

struct node
{
int vertex, dist;
node() {};
node(int v, int d) : vertex(v), dist(d) {};
};

bool operator < (node p, node q)
{
if(p.dist > q.dist)
return true;
else if(p.dist == q.dist)
{
if(p.vertex > q.vertex)
return true;
return false;
}
return false;
}

here .. the node priority is sorted according to distance, but when distance (suppose both are 0 ) is same then node is sorted according to the vertex number. for example it becomes

1 0
3 0
2 0
7 69
6 51
4 48    --> which is wrong

Thanks.
  • Проголосовать: нравится
  • -9
  • Проголосовать: не нравится

13 лет назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

No, overloading operators it's simply.
 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
#include <iostream>
#include <queue>

using namespace std;

struct node
{
    int vertex, dist;
    node() {};
    node(int v, int d) : vertex(v), dist(d) {};

    friend inline bool
    operator<(const node& p, const node& q)
    {
        return (p.dist > q.dist || (p.dist == q.dist && p.vertex > q.vertex));
    }
};

int main()
{
    priority_queue< node > q;
    
    q.push(node(1, 0));
    q.push(node(3, 0));
    q.push(node(2, 0));
    q.push(node(7, 69));
    q.push(node(6, 51));
    q.push(node(4, 48));
    
    while (!q.empty())
    {
        cout<< q.top().vertex<< " "<< q.top().dist<< "\n";
        q.pop();
    }
    
    return 0;
}