//median.hpp
//median函數模板在保存未知類型對象的vector中查找中間值
#ifndef MEDIAN_H_
#define MEDIAN_H_
#include<vector>
#include<algorithm>
using std::vector;
//如果vector中有中間值,則返回true,並將中間值記錄在第二個參數中
//否則,返回false
template <typename T>
bool median(const vector< T>& , T& );
#include "median.hpp"//引入函數模板的實現文件
#endif // MEDIAN_H_
//median.cpp
//定義median函數模板的實現文件(源文件)
#include<iostream>
#include<vector>
using std::vector;
template <typename T>
bool median(const vector<T>& c, T& m)
{
//構造temp爲c的副本
vector<T> temp(c);
//如果容器中包含偶數個元素,則沒有中間值,返回false
if(temp.size() % 2 == 0)
return false;
//將元素排序
sort(temp.begin(),temp.end());
//判斷中間點元素是否爲中間值,是則返回true,並用m記錄中間值
//否則返回false
typename vector<T>::size_type index = temp.size() / 2;
if(temp[index] > temp[index-1]
&& temp[index] < temp[index+1])
{
m = temp[index];
return true;
}
else
{
return false;
}
}
#include <iostream>
#include<vector>
#include "median.hpp"
#include "median.cpp"
using namespace std;
int main()
{
int ia1[] = {1,2,3,4,5,6,7};
int ia2[] = {1,2,3,4};
int ia3[] = {1,2,2,3,4,5,6};
vector<int> ivec1(ia1,ia1+7);
vector<int> ivec2(ia2,ia2+4);
vector<int> ivec3(ia3,ia3+7);
int m;
if(median(ivec1, m))
cout << "median: "<< m << endl;
else
cout << "no median: " << endl;
if(median(ivec2, m))
cout << "median: " << m << endl;
else
cout << "no median: " << endl;
if(median(ivec3, m))
cout << "median: " << m << endl;
else
cout << "median: " << endl;
return 0;
}
template <class elemType> class ListItem;
template <class elemType> class List
{
public:
List<elemType>();
List<elemType>(const List<elemType> &);
List<elemType>& operator=(const List<elemType> &);
~List();
void insert(ListItem<elemType> *ptr, elemType value);
ListItem<elemType> *find(elemType value);
private:
ListItem<elemType> *front;
ListItem<elemType> *end;
}
template <class Type>
Queue<Type>& Queue<Type>::operator = (const Queue &orig)
{
destroy();
copy_elem(orig);
return *this;
}
template <class Type>
Queue<Type>& Queue<Type>::operator = (const Queue &orig)
{
QueueItem<Type> *p = orig.head, *q;
while(p != 0)
{
q = new QueueItem<Type>(p -> item);
if(p == orig.head)
head = tail = q;
tail -> next = q;
tail = q;
p = p->next;
}
}