C++模版学习

模板分为函数模板和类模板两种.

1、使用模板写一个实现排序、输出功能的函数.
#include <iostream>
#include <string>

//泛型编程
template<typename T>
void sort(T aa[], int n)
{
	T temp;
	int i,j;
	for(i = 0; i<n-1; i++)
		for(j = 0; j<n-1-i; j++)
		{
			if(aa[j]>aa[j+1])
			{
				temp = aa[j];
				aa[j] = aa[j+1];
				aa[j+1] = temp;
			}
		}
}

//结果输出
template<typename T><span style="white-space:pre">	</span>//模板头,T是模板参数
void show(T aa[], int n)
{
	int i;
	for(i = 0; i<n; i++)
	{
		std::cout<<aa[i]<<"\t";
	}
	std::cout<<std::endl;
}

int main()
{
	int a[5] = {2, 4, 3, 6, 5};
	double b[5] = {2.1, 3.5, 1.2, 5.2, 6.9};
	char c[4] = {'b', 'a', 'A', 'z'};
	std::string d[3] = {"hi", "hello", "world"};

	sort(a, 5);		show(a, 5);
	sort(b, 5);		show(b, 5);
	sort(c, 4);		show(c, 4);
	sort(d, 3);		show(d, 3);
	return 0;
}

2、类模版实现一个简单的栈.
#include <iostream>
#include <string>

//一个简单的类模版,实现简单的栈的功能
template <typename T>
class Stack{
public:
	Stack():cnt(0){}
	~Stack(){}
	void Push(const T &temp) { a[cnt++] = temp; }	//入栈
	void Pop() { cnt--; }							//出栈
	T& GetTop() { return a[cnt-1]; }				//取栈顶元素
	bool Isempty() { return cnt==0; }			//判空
	int Size() { return cnt; }						//大小

private:
	T a[10];
	int cnt;
};

int main()
{
	Stack<int> aa;
	Stack<std::string> bb;

	aa.Push(1);	aa.Push(3);	aa.Push(2);	aa.Push(4);		//<---
	bb.Push("hello");	bb.Push("china");	bb.Push("world");
	
	while(!aa.Isempty())	{	std::cout<<aa.GetTop()<<" "; aa.Pop(); }
	std::cout<<std::endl;
	while(!bb.Isempty())	{	std::cout<<bb.GetTop()<<" "; bb.Pop(); }
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值