// a005.cpp : 定義控制臺應用程序的入口點。
//
//鏈表list<content> l;實質上指向content變量類型的指針,二迭代器就是一個指向鏈表各個位置的一個指針。所以,
//鏈表是一個指針,迭代器是一個指向指針的指針的指針。即雙重指針。
#include "stdafx.h"
#include <string>
#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
using namespace std;
class cl1
{
public:
char name[20];int age;
cl1(char name[20],int age)
{
this->age=age;
strcpy(this->name,name);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
list<cl1*> l; //申請類指針為成員的鏈表
for(; ;)
{
char name[20];
int age;
scanf("%s",&name);
scanf("%d",&age);
cl1*p1=new cl1(name,age);
l.push_back(p1); //把類指針加入鏈表
int tem;
printf("1->YES 2->NO");
scanf("%d",&tem);
if(tem==2){break;}
}
list<cl1*>::iterator it=l.begin(); //申請類指針類型的迭代器,并指向鏈表的begin位置
while(it != l.end())
{
printf("%s--%d--",(*it)->name,(*it)->age);//迭代器本質上是一個指針。在這兒指向鏈表
it++;
}
it=l.begin();
while(it!=l.end()) //當迭代器不是指向最后一個是-----------------------------------|
{ // |
delete(*it);//<-----清空迭代器內容。即鏈表,即cl1的指針,即清空cl1的內存----------|
it++;
}
l.clear();
return 0;
}
|