算法公共头文件

来源:互联网 发布:chromebook装windows 编辑:程序博客网 时间:2024/04/27 20:55
/*
 * Copyright (c) 2007 Lotomer
 * 作    者  : Lotomer
 * 文 件 名  : common.h
 * 创建时间  : 2007.4.12
 * 说    明  : 排序算法的公共部分
 */
/////////////////////////////////////////////////////////////////////////
#ifndef SORT_DEBUG
    #define SORT_DEBUG
#endif
#ifdef SORT_DEBUG
#include <iostream>
using std::cout;
using std::endl;
template<class Elem>
void Print(Elem arr[], int nStart, int nEnd)
{   
    for (int i = nStart; i <= nEnd; ++i)
    {
        cout<<arr[i]<<" ";
    }
    cout<<endl;
}
#endif  /*  ifdef SORT_DEBUG    */
//元素比较模板类
template<class T>
class Compare{
public:
 virtual bool operator()(T& t1, T& t2) = 0;
};
//继承模板类
//小于
template<class T>
class Lower : public Compare<T>{
public:
 bool operator()(T& t1, T& t2)
 {
  return t1 < t2;
 }
};
//大于
template<class T>
class Greater : public Compare<T>{
public:
 bool operator()(T& t1, T& t2)
 {
  return t1 > t2;
 }    
};
//-------------------------------------------------------
//交换元素
template<class Elem>
inline void swap(Elem arr[], int index_a, int index_b)
{
 Elem tmp = arr[index_a];
 arr[index_a] = arr[index_b];
 arr[index_b] = tmp; 
}
//重载
template<class Elem>
inline void swap(Elem &a, Elem &b)
{
    Elem tmp = a;
    a = b;
    b = tmp;
}
//部分特化
template<class Elem>
inline void swap(Elem* a, Elem* b)
{
    Elem* tmp = a;
    a = b;
    b = a;
}