一、代码
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
//主模板
template <typename T>
class Heap
{
public:
void push(const T& val);
T pop();
bool empty() const { return m_vec.empty(); }
private:
vector<T> m_vec;
};
template <typename T>
void Heap<T>::push(const T& val)
{
m_vec.push_back(val);
push_heap(m_vec.begin(), m_vec.end());
}
template <typename T>
T Heap<T>::pop()
{
pop_heap(m_vec.begin(), m_vec.end());
T tmp = m_vec.back();
m_vec.pop_back();
return tmp;
}
//完全特化 const char*
template <>
class Heap<const char*>
{
public:
void push(const char* val);
const char* pop();
bool empty() { return m_vec.empty(); }
private:
vector<const char*> m_vec;
};
bool strLess(const char* a, const char* b)
{
return strcmp(a, b) < 0;
}
void Heap<const char*>::push(const char* val)
{
m_vec.push_back(val);
push_heap(m_vec.begin(), m_vec.end(), strLess);
}
const char* Heap<const char*>::pop()
{
pop_heap(m_vec.begin(), m_vec.end());
const char* tmp = m_vec.back();
m_vec.pop_back();
return tmp;
}
//局部特化 指针类型 T*
template <typename T>
class Heap<T*>
{
public:
void push(T* val);
T* pop();
bool empty() { return m_vec.empty(); }
private:
vector<T*> m_vec;
};
template <typename T>
struct PtrCmp : public binary_function<T*, T*, bool>
{
bool operator()(const T* a, const T* b) const
{
return *a < *b;
}
};
template <typename T>
void Heap<T*>::push(T* val)
{
m_vec.push_back(val);
push_heap(m_vec.begin(), m_vec.end(), PtrCmp<T>());
}
template <typename T>
T* Heap<T*>::pop()
{
pop_heap(m_vec.begin(), m_vec.end());
T* tmp = m_vec.back();
m_vec.pop_back();
return tmp;
}
//
int main(int argc, char*argv[])
{
//主模板
Heap<int> h1;
h1.push(1);
h1.push(3);
h1.push(2);
cout<<"is empty: "<<h1.empty()<<endl;
cout<<h1.pop()<<endl;
cout<<h1.pop()<<endl;
cout<<h1.pop()<<endl;
cout<<"is empty: "<<h1.empty()<<endl<<endl;
//完全特化 const char*
Heap<const char*> h2;
h2.push("aa");
h2.push("cc");
h2.push("bb");
cout<<"is empty: "<<h2.empty()<<endl;
cout<<h2.pop()<<endl;
cout<<h2.pop()<<endl;
cout<<h2.pop()<<endl;
cout<<"is empty: "<<h2.empty()<<endl<<endl;
//局部特化 指针类型 T*
Heap<char*> h3;
h3.push("aa");
h3.push("bb");
h3.push("cc");
cout<<"is empty: "<<h3.empty()<<endl;
cout<<h3.pop()<<endl;
cout<<h3.pop()<<endl;
cout<<h3.pop()<<endl;
cout<<"is empty: "<<h3.empty()<<endl;
return 0;
}
二、输出结果
此时输出的3个结果都正确。