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;
}
相关推荐
Scott9999HH6 小时前
【IIoT流量实战】蒸汽管道阀门全关却仍有流量?用 Python 实现涡街信号 FFT 频谱分析与温压全补偿积算网关,深度拆解靠谱的涡街流量计厂家硬核技术标准
开发语言·python
2401_841495647 小时前
【操作系统】进程同步与互斥实验报告
c++·算法·操作系统·进程·并发·同步·互斥
fqbqrr7 小时前
2607C++,soui与安卓
c++·soui
码智社7 小时前
AES加密原理详解及Java实现加解密实战
java·开发语言
AI云海7 小时前
python 列表、元组、集合和字典
开发语言·python
萧瑟余晖8 小时前
JDK 26 新特性详解
java·开发语言
马优晨9 小时前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
fqbqrr11 小时前
2607C++,使用微软detours勾挂工具
c++
人邮异步社区11 小时前
怎么把C语言学到精通?
c语言·开发语言
心平气和量大福大11 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf