理解类模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//T是模板类型参数,size是非模板类型参数(都是const),必须是整形类(包括地址与引用)
template<typename T,int SIZE>
void sort(T *arr) //函数模板
{
for(int i=0;i<SIZE-1;i++)
{
for(int j=0;j<SIZE-1-i;j++)
{
if(arr[j]>arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
int main()
{
int arr[]={12,5,7,89,32,21,35};
const int size=sizeof(arr)/sizeof(arr[0]);
sort<int,size>(arr);
for(int val:arr)
{
cout<<val<<" ";
}
}

类模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

template<typename T>
class SeqStack //模板名称+类型参数列表=类名称
{
public:
//构造和析构 不用加类型参数列表,别的要加上类型参数列表
SeqStack(int size=10) //构造函数
:_pstack(new T[size])
,_top(0)
,_size(size)
{}
~SeqStack()
{
delete []_pstack;
_pstack=nullptr;
}
SeqStack(const SeqStack<T>&stack)
:_top(stack._top)
,_size(stack._size)
{
for(int i=0;i<_top;i++)
{
_pstack[i]=stack._pstack[i];
}
}
SeqStack<T>&operator=(const SeqStack<T>&stack)
{
if(this!=&stack)
{
return *this;
}
delete []_pstack;
_pstack=new T[stack._size];
_top=stack._top;
_size=stack._size;
for(int i=0;i<_top;i++)
{
_pstack[i]=stack._pstack[i];
}
return *this;
}
void push(const T &val);

void pop()
{
if(empty())
{
return;
}
_top--;
}
T top()const //对于只读,写成const,返回类型为const T
{
if (empty())
{
throw "stack is empty"; //抛出异常,不用管返回值
}
return _pstack[_top-1];
}

bool full()const
{
return _top==_size;
}

bool empty()const
{
return _top==0;
}


private:
T *_pstack;
int _top;
int _size;
void expand() //顺序栈底层数组按2倍的方式进行扩容
{
T *ptmp=new T[_size*2];
for(int i=0;i<_top;i++)
{
ptmp[i]=_pstack[i];
}
delete []_pstack;
_pstack=ptmp;
}
};
//类外实现成员方法,前面要有类作用域,但是这里已经不认识模板了
template<typename T>
void SeqStack<T>::push(const T &val)
{
if(full())
{
expand();

}
_pstack[_top++]=val;
}

int main()
{

SeqStack<int>stack;
stack.push(1);
stack.push(2);
stack.push(3);
stack.pop();
stack.pop();


}