函数模板
template
T function(T value1,T value2,T value3)
{
}
int i = 1;
int j = 2;
int k = 3;
function(i,j,k);
double m = 1.1;
double n = 2.2;
double l = 3.3;
function(m,n,l);
模板函数
#ifndef TSTACK1_H
#define TSTACK1_H
template
class Stack
{
public:
Stack(int = 10); //default constructure(stack size 10)
~Stack(){delete [] stackPtr;} //destructot
bool push(const T&); //push an elemnet onto the stack
bool pop(T&); //pop an element ohh the stakc
private:
int size; //#of elemnets in the stack
int top; //location of the top elemnet
T * stackPtr; //pointer to the stack
bool isEmpty() const {return top == -1;} //utility
bool isFull() const {return top == size - 1;} //functions
};
//constructure with default size 10
template
Stack< T >::Stack(int s)
{
size = s > 0 ? s : 10;
top = -1; //stack is initially empty
stackPtr = new T[size]; //allocate space for element
}
//push an element onto the stack
//return 1 if successful,0 otherwise
template
bool Stack< T >::push(const T &pushValue)
{
if(!isFull())
{
stackPtr[++top] = pushValue; //place item in stack
return true; //push successful
}
return false; //push unsuccessful
}
//pop an element off the stack
template
bool Stack< T >::pop(T &popValue)
{
if(!isEmpty())
{
popValue = stackPtr[top--]; //remove item from stack
return true; //pop successful
}
return false; //pop unsuccessful
}
#endif //TSTACK1_H
//Fig.12.3:stack.cpp
//Test driver for stack template
#include
using std::cout;
using std::cin;
using std::endl;
#include "stack.h"
int main()
{
Stack< double > doubleStack(5);
double f = 1.1;
cout << "pushing element onto doubleStack\n";
while(doubleStack.push(f))
{
cout << f <<" ";
f += 1.1;
}
cout << "\nStack is full.cannot push" << f
<< "\n\nPoping elements from doubleStack\n";
while(doubleStack.pop(f))
{
cout << f << " ";
}
cout << "\nStack is empty.cannot pop\n";
Stack< int > intStack;
int i =1;
cout << "\nPushing elemnets onto intStack\n";
while(intStack.push(i))
{
cout << i << " ";
++i;
}
cout << "\nStack is full.cannot push" << i
<< "\n\nPoping elements from doubleStack\n";
while(intStack.pop(i))
{
cout << i << " ";
}
cout << "\nstack is empty.cannot pop\n";
return 0;
}
阅读(658) | 评论(0) | 转发(0) |