1:Swap函数
template < class T >
void Swap ( T & a, T & b)
{
T temp = a;
a = b;
b = temp;
}
2 :输入输出排序
template < class T >
void Sort ( T arr[ ] , int len)
{
int i, j;
T tmp;
for ( i = 0 ; i < len - 1 ; i++ )
{
for ( j = 0 ; j < len - 1 - i; j++ )
{
if ( arr[ j] > arr[ j + 1 ] )
{
tmp = arr[ j] ;
arr[ j] = arr[ j + 1 ] ;
arr[ j + 1 ] = tmp;
}
}
}
}
template < class T >
void Output ( T arr[ ] , int len)
{
int i;
for ( i = 0 ; i < len; i++ )
{
if ( i < len - 1 )
{
cout << arr[ i] << ", " ;
}
}
cout << arr[ len - 1 ] << endl;
}
template < class T >
void Input ( T arr[ ] , int len)
{
for ( int i = 0 ; i < len; i++ )
{
cin >> arr[ i] ;
}
}
int main ( )
{
const int LEN = 5 ;
int type;
while ( std:: cin >> type)
{
switch ( type)
{
case 0 :
{
int a1[ LEN] ;
Input< int > ( a1, LEN) ; Sort< int > ( a1, LEN) ; Output< int > ( a1, LEN) ;
break ;
}
case 1 :
{
char a2[ LEN] ;
Input ( a2, LEN) ; Sort ( a2, LEN) ; Output ( a2, LEN) ;
break ;
}
case 2 :
{
double a3[ LEN] ;
Input ( a3, LEN) ; Sort ( a3, LEN) ; Output ( a3, LEN) ;
break ;
}
}
}
system ( "pause" ) ;
return 0 ;
}
3:Search
# include <iostream>
# include <string.h>
# include <fstream>
# include <string>
# include <algorithm>
using namespace std;
template < class T >
int Search ( const T * array, int arrayLen, const T & value)
{
for ( int i = 0 ; i < arrayLen; i++ )
{
if ( array[ i] == value)
{
return i;
}
}
return - 1 ;
}
int main ( )
{
int n;
std:: cin >> n;
int * nValues = new int [ n] ;
for ( int i = 0 ; i < n; i++ )
{
std:: cin >> nValues[ i] ;
}
int d;
std:: cin >> d;
std:: cout << Search ( nValues, n, d) << std:: endl;
delete [ ] nValues;
double f;
std:: cin >> n;
double * dValues = new double [ n] ;
for ( int i = 0 ; i < n; i++ )
{
std:: cin >> dValues[ i] ;
}
std:: cin >> f;
std:: cout << Search ( dValues, n, f) << std:: endl;
delete [ ] dValues;
std:: cin >> n;
char * cValues = new char [ n] ;
for ( int i = 0 ; i < n; i++ )
{
std:: cin >> cValues[ i] ;
}
char c;
std:: cin >> c;
std:: cout << Search ( cValues, n, c) << std:: endl;
delete [ ] cValues;
return 0 ;
}