]>
git.proxmox.com Git - ceph.git/blob - ceph/src/dmclock/support/src/heap.h
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
5 * Copyright (C) 2016 Red Hat Inc.
7 * Author: J. Eric Ivancich <ivancich@redhat.com>
9 * This is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU Lesser General Public License version
11 * 2.1, as published by the Free Software Foundation. See file
28 * T : type of data held in the heap.
30 * C : class that implements operator() with two arguments and
31 * returns a boolean when the first argument is greater than (higher
32 * in priority than) the second.
34 template<typename T
, typename C
>
46 iterator(Heap
<T
,C
>& _heap
, int _index
) :
55 iterator(iterator
&& other
) :
62 iterator
& operator++() {
67 bool operator==(const iterator
& other
) const {
68 return index
== other
.index
;
71 bool operator!=(const iterator
& other
) const {
72 return !(*this == other
);
76 return heap
.data
[index
];
79 // the item this iterator refers to
93 // parent(0) should be a negative value, which it is due to
94 // truncating towards negative infinity
95 static inline int parent(int i
) { return (i
- 1) / 2; }
97 static inline int lhs(int i
) { return 2*i
+ 1; }
99 static inline int rhs(int i
) { return 2*i
+ 2; }
106 if (!comparator(data
[i
], data
[pi
])) {
110 std::swap(data
[i
], data
[pi
]);
115 void siftDown(int i
) {
121 if (comparator(data
[li
], data
[i
])) {
122 if (ri
< count
&& comparator(data
[ri
], data
[li
])) {
123 std::swap(data
[i
], data
[ri
]);
126 std::swap(data
[i
], data
[li
]);
129 } else if (ri
< count
&& comparator(data
[ri
], data
[i
])) {
130 std::swap(data
[i
], data
[ri
]);
150 Heap(const Heap
<T
,C
>& other
) {
151 data
.resize(other
.data
.size());
152 for (int i
= 0; i
< other
.count
; ++i
) {
153 data
[i
] = other
.data
[i
];
158 const Heap
<T
,C
>& operator=(const Heap
<T
,C
>& other
) {
159 data
.resize(other
.data
.size());
160 for (int i
= 0; i
< other
.count
; ++i
) {
161 data
[i
] = other
.data
[i
];
167 bool empty() const { return 0 == count
; }
169 T
& top() { return data
[0]; }
173 data
.push_back(item
);
178 data
[0] = data
[--count
];
193 return iterator(*this, 0);
197 return iterator(*this, count
);
200 std::ostream
& displaySorted(std::ostream
& out
,
201 std::function
<bool(const T
&)> filter
,
202 bool insert_line_breaks
= true) const {
203 Heap
<T
,C
> temp
= *this;
208 while(!temp
.empty()) {
209 const T
& top
= temp
.top();
214 if (insert_line_breaks
) {
215 out
<< std::endl
<< " ";
224 if (insert_line_breaks
) {
230 template<typename T1
, typename T2
>
231 friend std::ostream
& operator<<(std::ostream
&, const Heap
<T1
,T2
>&);
235 template<typename T1
, typename T2
>
236 std::ostream
& operator<<(std::ostream
& out
, const Heap
<T1
,T2
>& h
) {
241 for (int i
= 1; i
< h
.count
; i
++) {
242 out
<< ", " << h
.data
[i
];