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
|
#include <algorithm>
#include <initializer_list>
#include <iostream>
#include <vector>
template <typename T, typename Compare> struct BinaryHeap;
template <typename T, typename Compare>
std::ostream& operator<< ( std::ostream& os, const BinaryHeap<T, Compare>& rhs );
template <typename T>
struct Comp {
bool operator()(const T& lhs, const T& rhs) const;
};
template <typename T>
bool Comp<T>::operator()(const T& lhs, const T& rhs) const
{
return lhs > rhs;
}
template <typename T, typename Compare = std::greater<T>>
struct BinaryHeap {
std::vector<T> v;
explicit BinaryHeap(std::initializer_list<T> v_arg);
//friend:
friend std::ostream& operator<< <> ( std::ostream& os,
const BinaryHeap<T, Compare>& rhs );
};
template <typename T, typename Compare>
BinaryHeap<T, Compare>::BinaryHeap(std::initializer_list<T> v_arg)
: v { v_arg }
{
std::sort(v.begin(), v.end(), Compare());
}
template <typename T, typename Compare>
std::ostream& operator<< ( std::ostream& os, const BinaryHeap<T, Compare>& rhs )
{
for ( const auto& e : rhs.v ) {
os << e << ' ';
}
return os;
}
int main()
{
BinaryHeap<int> bh_1 { 3, 5, 1, 4, 2 };
std::cout << bh_1 << '\n';
BinaryHeap<int, Comp<int>> bh_2 { 3, 5, 1, 4, 2 };
std::cout << bh_2 << '\n';
auto l_f { [](auto a, decltype(a) b) -> bool { return a > b; } };
BinaryHeap<int, decltype(l_f)> bh_3( { 3, 5, 1, 4, 2 } );
std::cout << bh_3 << '\n';
}
|