找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

帖子
查看: 1873|回復: 0
收起左側

鏈表迭代

[復制鏈接]
ID:104287 發(fā)表于 2016-1-31 02:49 | 顯示全部樓層 |閱讀模式
// a005.cpp : 定義控制臺應用程序的入口點。

//
//鏈表list<content> l;實質(zhì)上指向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);//迭代器本質(zhì)上是一個指針。在這兒指向鏈表
                it++;
        }
        it=l.begin();
        while(it!=l.end()) //當?shù)鞑皇侵赶蜃詈笠粋€是-----------------------------------|
        {                                //                                                                                                |
        delete(*it);//<-----清空迭代器內(nèi)容。即鏈表,即cl1的指針,即清空cl1的內(nèi)存----------|
        it++;
        }
        l.clear();
        return 0;
}



回復

使用道具 舉報

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術交流QQ群281945664

Powered by 單片機教程網(wǎng)

快速回復 返回頂部 返回列表