cc33a_demo-33CppPrimer_模板与泛型编程-16.01-基础知识
//##-两种模板
//*类模板。函数模板
//为什么要用类模板?
//当调用Queue<int> a时,它就只能增加int的数据,如果Queue<double> q2,double时,得再写一个dobule的类。如果string,则再写一个string类
//用一个类模板,就可以把所有类型都包括了。很方便。
//##-泛型编程-独立于任何特定类型的方式进行编程。
//*主要用于容器,迭代器,算法->C++ STL标准模板库
//##-示例
//1.普通队列--q.h
//2.c++中的泛型容器-vector,list,set...
//3.顺序队列 //内部是数组--类模板
//4.链式队列 //内部是链表--类模板
#include <iostream>//txwtech-cc33a_demo.cpp-33CppPrimer_模板与泛型编程-16.01-
#include "q.h"
//#include "q2.h"
#include <string>
#include <vector>
#include <list>
#include <set>
using namespace std;
//##-两种模板
//*类模板。函数模板
//为什么要用类模板?
//当调用Queue<int> a时,它就自能增加int的数据,如果Queue<double> q2,double时,得再写一个dobule的类。如果string,则再写一个string类
//用一个类模板,就可以把所有类型都包括了。很方便。
//##-泛型编程-独立于任何特定类型的方式进行编程。
//*主要用于容器,迭代器,算法->C++ STL标准模板库
//##-示例
//1.普通队列--q.h
//2.c++中的泛型容器-vector,list,set...
//3.顺序队列 //内部是数组--类模板
//4.链式队列 //内部是链表--类模板
int main()
{
Queue a; //普通队列--q.h
//Queue a;
//Queue<double> q2;
//Queue<string> q3;
a.push(10);//普通队列--q.h
a.push(20);//普通队列--q.h
a.push(30);//普通队列--q.h
a.print();//普通队列--q.h
vector<int> v1;
vector<double> v2;
vector<string> v3;
v1.push_back(10);
v1.push_back(20);
v2.push_back(1.2);
v2.push_back(9.8);
v3.push_back("hello");
v3.push_back("bill1");
list<int> aa; //容器都采用的是类模板
list<string> b;
aa.push_back(100);
aa.push_back(200);
b.push_back("dog");
b.push_back("cat");//都是泛型,用的类模板
getchar();
return 0;
}
q.h
#pragma once
#include <iostream>//q.h头文件txwtech
#include <iomanip>
using namespace std;
//template<class T> //模板参数。T代表任一类型,就是泛型,随便取名,可以T1,TT...
class Queue //普通队列
{
struct Node
{
int a;
Node * next;
};
public:
Queue();
void push(int b);
void pop();
int getlength();
virtual void print();
private:
Node * head;
Node * rear;
};
//template<class T>
void Queue::push(int b)
{
Node *p1 = new Node;
p1->a = b;
p1->next = NULL;
rear->next = p1;
rear = p1;
head->a++;
cout << setw(2) << b << setw(2) << "进入队列" << endl;
}
//template<class T>
void Queue::pop()
{
Node *p;
p = head->next;
cout << " " << setw(2) << p->a << setw(2) << "出队" << endl;
head->next = p->next;
delete p;
head->a--;
}
//template<class T>
int Queue::getlength()
{
return head->a;
}
//template<class T>
void Queue::print()
{
Node *p;
p = head->next;
cout << "队列中的元素是:" << endl;
while (p)
{
cout << p->a<< "->";
p = p->next;
}
cout << "NULL" << endl;
}
//template<class T>
Queue::Queue()
{
rear = head = new Node();
};