好久没写C++没用STL了,今天在STLChina泡了一下午。完整的代码只写了这么一个,贴上来吧。
  写了两个类,Max_Heap和Min_Heap,以他们特例化priority_queue,可以方便地实现最大、最小堆。写完了忽然又觉得这俩类似乎是多此一举了,完全可以用greater来实现最小堆,但由priority_queue的模板定义看出,那样就必须提供一个容器类型,比如vector
  最后还写了测试用例:找出n个数中最大的k个。

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
template < class T, class Container = vector<T>,
           class Compare = less<typename Container::value_type> > class priority_queue;
 
explicit priority_queue ( const Compare& x = Compare(),
                          const Container& y = Container() );
template <class InputIterator>
         priority_queue ( InputIterator first, InputIterator last,
                          const Compare& x = Compare(),
                          const Container& y = Container() );
*/
#include <iostream>
#include <queue>
using namespace std;
 
struct Max_Heap
{
    Max_Heap(int n): _n(n) {}
    operator int() { return _n;} //在需要的地方隐式类型转换
    int _n;
};
 
struct Min_Heap
{
    Min_Heap(int n): _n(n) {}
    operator int() { return _n;} //在需要的地方隐式类型转换
    int _n;
};
bool operator < (Max_Heap l, Max_Heap r) //~ 正常的<
{
    return l._n < r._n;
}
 
bool operator < (Min_Heap l, Min_Heap r) //~ 反义的<
{
    return l._n > r._n;
}
 
int
main (int argc, char **argv)
{
    priority_queue<Min_Heap> heap; //~ 最小堆
    //priority_queue<Max_Heap> heap; //~ 最大堆
    //~ 测试用例
    //~ 前K个最大值
    int k = 5;
    int tmp;
    for (int i = 0; i < k; ++i)
    {
        cin>>tmp;
        heap.push(tmp);
    }
    while (cin>>tmp)
    {
        if(tmp > heap.top()._n)
        {
            heap.push(tmp);
            heap.pop();
        }
    }
    cin.clear();
    while (heap.size())
    {
        cout<<heap.top()._n<<' ';
        heap.pop();
    }
    return 0;
}
Tags: ,,.
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Home

Be the first to comment on this entry.

Name(required)
Mail (required),(will not be published)

RFC: Request For Comments. Orz..

Website(recommended)