-2

What is the problem?

When I use priority queue of STL, I want to use min heap, so I used like below code.

It works on default option but it is not working on "greater option".

enter image description here

It always arranges like above picture. I don't know totally why this happened.

struct node {
    string code;
    int fre;

    bool operator<(const node& rhs) const {
        return fre < rhs.fre;
    }

    bool operator>(const node& rhs) const {
        return fre > rhs.fre;
    }
};

std::priority_queue<node, vector<node>, greater<node>> q;
std::map<node,int> huffman_tree;

int main(void)
{
    int f;
    for (int i = 1; i <= n; i++) {
        string c;
        std::cin >> c >> f;
        node huffman = { c,f };
        q.push(huffman);
    }

    q.pop();

    return 0;
}
molamola
  • 269
  • 4
  • 15
  • 4
    so what's your real problem again? – Joseph D. Apr 09 '18 at 07:26
  • Unrelated to your problem, but you have a weird of C and C++ regarding the input. Why do you use `scanf` and character arrays rather than the much safer `std::cin` and `>> ` operators (for input) and `std::string` (for strings)? – Some programmer dude Apr 09 '18 at 07:27
  • 7
    "Not working" and "compiler occurs error" are not useful problem statements. What happens *exactly*? Post the exact error message. – StoryTeller - Unslander Monica Apr 09 '18 at 07:27
  • 2
    More related to your problem, please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). Then edit your question to tell us *what* the problem is. *How* "it is not working". And also please read http://idownvotedbecau.se/itsnotworking/ – Some programmer dude Apr 09 '18 at 07:28
  • How do you know it is not working? What happens that you didn't expect? – Galik Apr 09 '18 at 07:50
  • Seems to work for me. Perhaps you didn't know that the `std::priority_queue` put the highest value (priority) at the top? – Galik Apr 09 '18 at 07:55
  • Sorry for poor question and no response. I went somewhere. I edited can you see? – molamola Apr 09 '18 at 10:06

1 Answers1

2

If I understand your problem correctly, you are looking at a priority queue in a debugger and are confused as to why the items in the queue are not stored in the order you expected.

Priority queues do not guarantee to store items in priority order. They only guarantee to give you back items in priority order when you pop them off the queue. Keeping items in priority order would mean that it would have to perform a sort operation every time a new item what put on the queue, which would be inefficient. Instead, priority queues typically use a data structure called a heap to manage the queue, which allows for much more efficient insertions into the queue.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299