#include "stdafx.h"
#include <iostream.h>
#include <string.h>
template <class T>
class Vector
{
T *v;
int sz;
public:
Vector(int s)
{
v=new T[s];
sz=s;
}
int size( )
{
return sz;
}
T& operator[] (int i)
{
return elem(i);
}
T& elem(int i)
{
return v[i];
}
void PrintAll()
{
for ( int i = 0 ; i < sz ;i ++ )
{
cout << v[i] << endl;
}
}
};
template<class T>
void sort(Vector<T>& v)
{
int n = v.size( );
for( int i=0; i<n-1; i++ )
{
for( int j=n-1; i<j; j-- )
{
if( Comp<T>::LessThan(v[j],v[j-1]) )
{
T temp = v[j];
v[j] = v[j-1];
v[j-1] = temp;
}
}
}
}
template<typename T>
class Comp
{
public:
static int LessThan( T i, T j)
{
return i<j;
}
};
//特殊版本的类
//template< > class Comp<char*>
//class Comp<char*>
class Comp<char*>
{
public:
static int LessThan( char* i, char* j)
{
return (strcmp(i,j)<0);
}
};
/*
//函数特例
void sort(Vector<char*>& v)
{
int n = v.size( );
for( int i=0; i<n-1; i++)
{
for( int j = n-1; i<j; j--)
{
if( strcmp(v[j],v[j-1]) <0 )
{
char* temp = v[j];
v[j] = v[j-1];
v[j-1] = temp;
}
}
}
}
*/
template< typename T, typename CompT >
class SortClass
{
public:
static void Sort( Vector<T> v );
};
template< typename T, typename CompT >
void SortClass<T,CompT>::Sort( Vector<T> v )
{
int n = v.size( );
for( int i=0; i<n-1; i++)
{
for( int j=n-1; i<j; j--)
{
if( CompT::LessThan( v[j],v[j-1] ) )
{
T temp = v[j];
v[j] = v[j-1];
v[j-1] = temp;
}
}
}
}
class Person
{
public:
Person():m_nAge(0){};
Person(int n):m_nAge(n){};
void SayHello()
{
cout << "Age is " << m_nAge << endl;
}
~Person()
{
cout << "~Person()" << endl;
}
private:
int m_nAge;
};
//通用版本的智能指针
template< typename T >
class SMartPtr
{
T* m_ptr;
public:
SMartPtr( T* ptr )
{
m_ptr = ptr;
}
T* operator->()
{
return m_ptr;
}
~SMartPtr()
{
if ( m_ptr )
{
delete m_ptr;
m_ptr = NULL;
}
}
};
int main(int argc, char* argv[])
{
//容器类 只管理操作一个指针
SMartPtr<Person> theSmart(new Person);
theSmart->SayHello();
Vector<char*> theVec(3);
theVec[0] = "Hello";
theVec[1] = "Wolrd";
theVec[2] = "C++";
theVec.PrintAll();
//sort<char*>( theVec );
SortClass<char*,Comp<char*> >::Sort(theVec);
theVec.PrintAll();
return 0;
}