C++:迭代器

迭代器的本质:对象。

迭代器与指针类似,通过迭代器可以指向容器中的某个元素,还可以对元素进行操作。

迭代器统一规范了遍历方式。不同的数据结构可以用统一的方式去遍历。

接下来是一个自定义迭代器的代码示例。

cpp 复制代码
#include<iostream>
using namespace std;

struct List
{
	int n;
	List* pnext;
};

void AddNode(List*& rpHead, List*& rpEnd, int n)
{
	List* ptemp = new List;
	ptemp->n = n;
	ptemp->pnext = NULL;
	if (NULL == rpHead)
	{
		rpHead = ptemp;
	}
	else
	{
		rpEnd->pnext = ptemp;
	}
	rpEnd = ptemp;
}

class Iterator//自定义的一个迭代器
{
private:
	List* p;
public:
	Iterator(List* p)
	{
		this->p = p;
	}
public:
	bool operator != (List* p)
	{
		if (this->p != p)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	int operator*()
	{
		return p->n;
	}
	List* operator++(int)
	{
		List* pTemp = p;
		p = p->pnext;
		return pTemp;
	}
};
int main()
{
	List* pHead = NULL;
	List* pEnd = NULL;

	AddNode(pHead, pEnd, 1);
	AddNode(pHead, pEnd, 2);
	AddNode(pHead, pEnd, 3);
	AddNode(pHead, pEnd, 4);

	/*while (pHead != NULL)//原本的链表遍历方式
	{
		cout << pHead->n << endl;
		pHead = pHead->pnext;
	}*/

	Iterator ite = pHead;
	while (ite != NULL)
	{
		cout << *ite << endl;
		ite++;
	}

	return 0;
}
相关推荐
端平入洛1 天前
delete又未完全delete
c++
端平入洛2 天前
auto有时不auto
c++
埃博拉酱2 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code
唐宋元明清21883 天前
.NET 本地Db数据库-技术方案选型
windows·c#
郑州光合科技余经理3 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1233 天前
matlab画图工具
开发语言·matlab
加号33 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
dustcell.3 天前
haproxy七层代理
java·开发语言·前端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20213 天前
信号量和信号
linux·c++