模板 Templates
泛型Generic Programming是指具有在多种数据类型上皆可操作的含意。
标准模板库 STL
函数模板
#include <iostream>
using namespace std;
void Swap(int &a, int &b)
{
int t = a;
a = b;
b = t;
}
void Swap(double &a, double &b)
{
double t = a;
a = b;
b = t;
}
void Swap(long &a, long &b)
{
long t = a;
a = b;
b = t;
}
// 函数模板 根据具体的类型产生模板函数
template<typename T>
void Swap(T &a, T &b)
{
T t = a;
a = b;
b = t;
}
int main()
{
double a = 4; double b = 5;
cout<<a<<b<<endl;
Swap(a, b);
cout<<a<<b<<endl;
return 0;
}
类模板
典型的数据结构之一,底层的存储空间类型一致
push进去的数据跟底层保持一致
pop出来的数据跟底层保持一致
可增加template<typename T> 并将int 改为T
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
class Stack
{
public:
Stack(int size=1024);
~Stack();
bool isEmpty();
bool isFull();
void push(int data);
int pop();
private:
int * space;
int top;
};
Stack::Stack(int size)
{
space = new int[size];
top = 0;
}
Stack::~Stack()
{
delete []space;
}
bool Stack::isEmpty()
{
return top = 0;
}
bool Stack::isFull()
{
return top = 1024;
}
void Stack::push(int data)
{
space[top++] = data;
}
int Stack::pop()
{
return space[--top];
}
int main()
{
Stack s(100);
if(!s.isFull())
s.push(10);
if(!s.isFull())
s.push(20)
while(!s.isEmpty())
cout<<s.pop()<<endl;
return 0;
}
Stack<T>::Stack(T size)
Stack<int> s(100);
例如:
vector<int> vi;
for(int i = 0; i < 10; i++)
vi.push_back(i);
for(int i = 0; i < vi.size(); i++)
cout<<vi[i]<<endl;
Vector 可以自定义设置内存策略