天天看點

C++學習筆記之模闆篇

一、模闆

不管是函數模闆還是類模闆,在未初始化前都是不占用記憶體的。 另外一般來說模闆代碼不能分開編譯,即不能分開寫成.h檔案和.c檔案,需要寫成一個檔案。

函數模闆

關鍵字:

  • template:用于聲明模闆
  • typename,class:聲明類型,作用相同,不過建議用typename

1.類型作為模闆參數

舉個例子:

template <class T>
T max(T a,T b)
{
	return (a>b)?a:b;
}

int ival = max<int>(100,99);
           

2.變量作為模闆參數

template <int size>
void display()
{
	cout<<size<<endl;
}

display<10>();
           

3.多參數函數模闆

舉個例子

template <typename T,typename C>
void display(T t,C c)
{
	cout<<t<<c<<endl;
}

int a = 666;
string str = "marsggbo";
dispaly<int,string>(a,str);
           

4.資料類型和變量混用

還是舉個栗子:

template <typename T,int size>
void display(T t)
{
	int i = 0;
	while(i++<size)
	{
		cout<<t<<endl;
	}
}

dispaly<int,6>(6);
           

類模闆

template <typename T>
class A
{
public:
    A(T a);
    T display()
    {
        return A.a;
    }
private:
    T a;
}
           

每定義一個成員函數時都需要在前面加上template關鍵字,另外在類名後還需要加上類型,即 <T> ,舉個栗子:

template <typename T>
A::A(T x)
{
    A.a = x;
}

template <typename T>
T A<T>::display()
{
...
}
           

執行個體化類模闆

int main(void)
{
    A<int> test;
    test.display();
    
    return 0;
}
           

二、标準模闆庫

1. vector

  • vector初始化
  • vector常用函數

特别注意,end() 傳回的是向量疊代器末元素的下一個元素,是以如果要通路最後一個元素,表達式是這樣的:

*

(--vector.end()) ,(ps:注意前面有個*号)

代碼示例:

記得引入vector頭檔案

#include <iostream>
#include <vector>
using namespace std;

int main (void)
{
    vector<int> vec(6,6);   // 初始化為6個6
    vec.push_back(5);   // 在末尾插入一個資料
    cout<<vec.size()<<endl; //vector的長度(資料數量)
    vec.pop_back();     // 删除末尾的一個資料
    cout<<vec.size()<<endl;

    // 周遊
    for(int i=0;i<vec.size();i++)
    {
        cout<<vec[i]<<endl;
    }
    return 0;
}
>>>
7
6
6
6
6
6
6
6

           

2.疊代器

疊代器相當于指針,要想通路資料,需要加上

直接看栗子吧

int main(void)
{
    vector<string> vec(2,"hello ");
    vec.push_back("marsggbo");
    vector<string>::iterator citer = vec.begin();
    cout<<*(--vec.end())<<endl; 
    for(;citer!=vec.end();citer++){
    	cout<< *citer << endl;
    }
    	
    return 0;
} 
>>>
marsggbo
hello
hello
marsggbo
           

3.連結清單list

注意連結清單周遊的時候不能使用取下标的方式,隻能通過疊代器進行周遊。

int main(void)
{
	list<int> t;
	t.push_back(6);
	t.push_back(65);
	t.push_back(66);
		
	list<int>::iterator itor = t.begin();
	for(;itor!=t.end();itor++)
	{
		cout<<*itor<<endl;
	}
	return 0;
} 
           

4.映射map

這個有點類似于Python中的字典。使用的關鍵字是map和pair

使用示例:

int main(void)
{
	map<int,string> m;
	pair<int ,string> p1(666,"marsggbo");
	pair<int ,string> p2(222,"hexin");
	m.insert(p1);
	m.insert(p2);
	
	cout<<m[666]<<endl;
	cout<<m[222]<<endl;		
	return 0;
} 
>>>
marsggbo
hexin
           

map的周遊方法:(還是以上面的例子做基礎)

int main(void)
{
	map<int,string> m;
	pair<int ,string> p1(666,"marsggbo");
	pair<int ,string> p2(222,"hexin");
	m.insert(p1);
	m.insert(p2);
	
	map<int,string>::iterator itor = m.begin();
	for(;itor!=m.end();itor++)
	{
	    cout<< itor->first <<":";     // 輸出鍵
	    cout<< itor->second << endl;    // 輸出值
	}
} 

>>>
222:hexin
666:marsggbo
           

MARSGGBO ♥原創 2017-4-6