迭代器
Stl中心思想:将算法和数据容器分开,彼此设计独立。最后再撮合在一起,容器和算法的泛型化(class template和function template分别对应)
#include<vector>
#include<list>
#include<deque>
#include<algorithm>
#include<iostream>
using namespacestd;
int main()
{
const int arraySize=7;
int ia[arraySize]={0,1,2,3,4,5,6};
vector<int> ivect(ia,ia+arraySize);
list<int>ilist(ia,ia+arraySize);
deque<int>ideque(ia,ia+arraySize);
vector<int>::iteratoritl=find(ivect.begin(),ivect.end(),4);
if(itl==ivect.end())
cout<<"4 notfound"<<endl;
else
cout<<"4found."<<*itl<<endl;
list<int>::iteratorit2=find(ilist.begin(),ilist.end(),6);
if(it2==ilist.end())
cout<<"6 notfound."<<endl;
else
cout<<"6found.!"<<*it2<<endl;
deque<int>::iteratorit3=find(ideque.begin(),ideque.end(),8);
if(it3==ideque.end())
cout<<"8 notfound."<<endl;
else
cout<<"8found."<<*it3<<endl;
cin.get();
return 0;
}
算法find()接收两个迭代器和一个搜寻目标。
迭代器是一种smart pointer。指针最重要的工作是内容提领和成员访问。迭代器的最重要工作就是对operator*和operator->进行重载。
Auto_ptr:
C++的auto_ptr所做的事情,就是动态分配对象以及当对象不再需要时自动执行清理。
使用std::auto_ptr,要#include<memory>。
源代码:
template <class T>
class auto_ptr
{
private:
T *ap;
public:
explicitauto_ptr(T *ptr=0)throw():ap(ptr){}
~auto_ptr()throw(){ delete ap}
//用来接收所有权
T *release()throw()
{
T *tmp(ap);
ap=0;
returntmp;
}
//用来接收所有权
voidreset(T *ptr=0)throw()
{
if(ap!=ptr)
{
deleteap;
ap=ptr;