1.首先我們看看怎麼使用
#include"stdafx.h"
#include<iostream>
#include<list>
#include<algorithm>
usingnamespacestd;
int_tmain(intargc,_TCHAR*argv[])
{
list<int>iList;
iList.push_back(1);
iList.push_back(2);
iList.push_back(7);
iList.push_back(4);
iList.push_back(5);
iList.push_back(3);
iList.push_back(10);
cout<<iList.size()<<endl; //相對于vector來說list是沒有capacity的(使用的是指針)
list<int>::iteratorit;
for(it= iList.begin();it!= iList.end();++it)
cout<<*it<<" ";
cout<<endl;
it= find(iList.begin(),iList.end(),5); //找到第五個位置的泛型指針
iList.insert(it,1000);
for(it= iList.begin();it!= iList.end();++it)
cout<<*it<<" ";
cout<<endl;
it= find(iList.begin(),iList.end(),1); //find不是list的類函數
iList.erase(it);
for(it= iList.begin();it!= iList.end();++it)
cout<<*it<<" ";
cout<<endl;
iList.pop_back(); //減少一個資料
iList.pop_back();
for(it= iList.begin();it!= iList.end();++it)
cout<<*it<<" ";
cout<<endl;
getchar();
return0;
}
2.簡單的封裝list
List的源代碼比vector的難度要打一些,其中涉及到指針,連結清單(雙向循環連結清單)
隻是簡單的封裝了幾個函數(參考資料結構)
#include"stdafx.h"
#include<iostream>
usingnamespacestd;
template<classT>
classListNode //定義節點類
{
public:
typedefListNode<T>*pListNode;
private:
pListNodeNext;
Tvalue;
public:
ListNode(constT&val,pListNodeN=NULL):value(val),Next(N){};
~ListNode(){};
ListNode():Next(NULL){};
};
template<classT>
classList; //前置聲明
template<classT>
classListIterator
{
public:
typedefListNode<T>*pListNode;
typedefListNode<T>&rListNode;
typedefList<T>*pList;
typedefList<T>&rList;
private:
constpListNodehead;
pListNodepCur; //目前的節點
public:
ListIterator():head(NULL)
{
if(pCur)
pCur= head;
pCur= head->Next;
}
~ListIterator(){};
intFind(constT&val)
{
pListNodep= head->Next;
while(p!=NULL&& !(p->value==val))p= p->Next;
if(p== NULL)return0;
pCur= p;
return1;
}
voidinsert(constT&val)
{
pListNodep;
p= newListNode<T>(val,pCur->next);
pCur= pCur->Next= p;
}
voidIsFound(constT&val)
{
pListNodep= head->Next;
while(p!=NULL&& !(p->value==val))p= p->Next;
returnp!= NULL;
}
intremove(constT&val)
{
pListNodep= head;
while(p->Next!=NULL&&!(p->value==val))p=p->Next;
if(p->Next==NULL) return0;
pListNodepL= p->Next;
p->Next= p->Next->Next;
deletepL;
pCur= head;
return1;
}
constListIterator&operator=(constListIterator&it)
{
if(this==&it)
return*this;
pCur= it.pCur;
return*this;
}
voidoperator++()
{
pCur= pCur->Next;
}
};
template<classT>
classList
{
public:
typedefListNode<T>*pListNode;
typedefListNode<T>rListNode;
typedefListIterator<T>lt;
pListNodehead; //定義頭結點
public:
List()
{
head= newrListNode();
}
~List()
{
deleteAllNode();
deletehead;
head->Next= NULL;
}
voiddeleteAllNode() //循環删除所有節點
{
pListNodep;
pListNodepNext;
for(p=head->Next;p!= NULL;p=pNext)
{
pNext= p->Next;
deletep;
}
}
constList&operator=(constList&src)
{
if(this==&src)
return*this;
deleteAllNode();
pListNodep=head;
pListNodepSrc= src.head;
ListIterator<T>it(*this);
while(pSrc!=NULL)
{
it.insert(pSrc->value);
pSrc= pSrc->Next;
}
return*this;
}
intIsEmpty()const
{
return(head->Next== NULL);
}
};