模板类:
template在写代码的时候可以减少代码的重复
#include <iostream>
#include <vector>
using namespace std;
template<class T>
class table{
public:
T a,b;//a,b的类型是T型
//如果写类型是浮点数呢?就造成了代码的重复
};
int main(){
table<int> t;//尖括号a里面要指明类型
t.a=10;
t.b=15;
//如果需要一个浮点型的桌子呢?
table<double> tt;
tt.a=3.5;
tt.b=3.5;
return 0;
}
这是一个最简答实际例子。上海交大的俞勇老师的数据结构算法都是用模板写的。可以多看看哦!
泛型编程,可以减少写代码。直接调用写好的库函数。
通常有很多vector,stack,list,algorithm,deque,set等等等等。以后会继续展开讲
#include <iostream>
#include <vector>
using namespace std;
vector<int> v;
v.push_back(123);
v.push_back(456);
for(int x:v){
cout<<x<<endl;
}
// vector里面的类型可以是int,能不能扔进行一个类的对象呢?
// 当然可以。
return 0;
}
下面是引入对象是例子:在前面讲到,vector虽然是模板,但是类型仅仅可以是int嘛?其实自己创建的对象也是可以的!
#include <iostream>
#include <vector>
using namespace std;
class student{
private:
string id;
int score;
public:
Stu(string id,int score){
this->id=id;
this->score=score;
}
friend ostream& operator<< (ostream &o,const Stu& s);
};
ostream& operator<< (ostream &o,const Stu& s){
o<<"("<<s.id <<","<<s.score<<")";
}
int main(){
Stu zs("s001",95);
cout<<zs;
return 0;
}
那么怎么将学生类的信息压入向量中呢?push_back是一个好的方法,但是使得对象创建了一次,又拷贝了一次。这样是不高效的。
#include <iostream>
#include <vector>
using namespace std;
class student{
private:
string id;
int score;
public:
Stu(string id,int score){
this->id=id;
this->score=score;
}
friend ostream& operator<< (ostream &o,const Stu& s);
};
ostream& operator<< (ostream &o,const Stu& s){
o<<"("<<s.id <<","<<s.score<<")";
}
int main(){
vector<Stu> s;//定义一个学生的向量,类似于容器
// 使用emplace_back(),可以在向量里面就地的去构造,避免了对象拷贝
s.emplace_back("S001",95);
s.emplace_back("Y009",100);
//直接cout不可以
for(auto x:s){
cout<<x<<endl;
}
//-----------------------------------------------------
//Stu zs("s001",95);
/// s.push_back(zs); //如果这样写多了一次拷贝
//cout<<zs;
}
跑出来结果如下:
后序文章还是会表示友元函数的相关概念,并且贴上相应的代码!