easy way to maintain a min heap with stl?

后端 未结 3 1312
一生所求
一生所求 2021-02-01 06:32

for user defined struct, as I understand, it\'s easy. Just overload the operator <. However, for int/float etc.., do I really need to overload operator < for int? Here is

3条回答
  •  盖世英雄少女心
    2021-02-01 06:49

    The answers are good, so I just wanted to add a small example. Say you have the following array:

    array A{5,2,8,3,4,1,9,12,0,7};
    

    and you want to create a min heap. The quickest way to do that is to use make_heap algorithm. However, that creates a max heap by default. In other words, if you call:

    make_heap(A.begin(), A.end());
    

    A becomes a max heap. To have a min heap, on the other hand, you need to add a comparator but do not need to implement one. Instead call the method as follows:

    make_heap(A.begin(), A.end(), greater());
    

    This call will make your array a min heap.

    PS: #include is necessary to use std::make_heap. Same operations apply to the vector as well.

    HTH!

提交回复
热议问题