1. 函數(shù)模版
函數(shù)模版和類模板,泛型編程
創(chuàng)建一個通用函數(shù),其返回值和形式參數(shù)可以指定,用一個虛擬的類型代表。
語法:
template <typename T>
函數(shù)聲明或定義
template<typename T>
void swapValue(T &a, T &b) {
T temp = a;
a = b;
b = temp;
}
typename可以替換為class。
2. 普通函數(shù)和模版函數(shù)的調(diào)用規(guī)則
如果普通函數(shù)和模版函數(shù)都可以調(diào)用,優(yōu)先調(diào)用普通函數(shù)。
通過空模版參數(shù)列表可以強制調(diào)用模版函數(shù)。比如:swapValue<>(a, b)。
函數(shù)模版也可以發(fā)生函數(shù)重載。
如果函數(shù)模版能產(chǎn)生更好的匹配,優(yōu)先調(diào)用函數(shù)模版。
3. 類模版
語法:
template<class T>
類
template<class NT, class AT>
class Person {
public:
Person(NT name, AT age) {
this->name = name;
this->age = age;
}
NT name;
AT age;
};
Person<string, int> p("ssd", 12);
類模版沒有自動類型推導的使用方式。
類模版在模版參數(shù)列表中可以有默認參數(shù)類型。
類模版中的成員函數(shù)一開始不會創(chuàng)建,在調(diào)用時才去創(chuàng)建。
4. 類模版對象做函數(shù)參數(shù)
指定傳入類,參數(shù)模版化,整個類模版化
5. 類模板與繼承
class Child: public Person<string, int> {
};
template<class T1, class T2>
class Audlt: public Person<T1, T2> {
};
6. 類模版成員函數(shù)類外實現(xiàn)
template<class T1, class T2>
class Person {
public:
Person(T1 t1, T2 t2);
// {
// this->t1 = t1;
// this->t2 = t2;
// }
void showPerson();
// {
// cout << t1 << t2 << endl;
// }
T1 t1;
T2 t2;
};
template<class T1, class T2>
Person<T1, T2>:: Person(T1 t1, T2 t2) {
this->t1 = t1;
this->t2 = t2;
}
template<class T1, class T2>
void Person<T1, T2>::showPerson() {
cout << t1 << t2 << endl;
}
7. 標準模版庫STL
STL可以分為六大組件:容器,算法,迭代器,仿函數(shù),適配器,空間配置器。
8. vector數(shù)組
void test() {
// 創(chuàng)建數(shù)組
vector<int> v;
// 插入數(shù)據(jù)
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
// 迭代器
vector<int>::iterator itBegin = v.begin();
vector<int>::iterator itEnd = v.end();
// 遍歷
while (itBegin != itEnd)
{
cout<< *itBegin << endl;
itBegin++;
}
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout<< *itBegin << endl;
}
for_each(v.begin(), v.end(), method);
}
9. string容器
char *是一個指針,string是一個類,內(nèi)部封裝了char *
string賦值操作:=號,assign
void test01() {
string s;
s = "123";
string s3;
s3 = s;
s3.assign("345");
string s1("111");
const char * str = "hello";
string s2(str);
}
字符串拼接:+=,append
void test02() {
string s;
s = "1";
s += "2";
s.append("3");
cout << s << endl;
}
字符串查找和替換:find, replace。
字符串比較compare,返回值等于0表示相等,大于0表示大于,小于0表示小于。
字符存取,str[i] 和str.at(i)可以存取特定位置的字符。
insert和erase可以插入和刪除字符串。
substr獲取子串
9. vector數(shù)組
vector可以動態(tài)擴展。