STL迭代器(iterator)

本文介绍了STL中的迭代器,它作为容器与算法之间的桥梁,有五种类型。迭代器模式允许顺序访问聚合对象的元素而不暴露其内部结构。在STL中,迭代器如同智能指针,重载了`operator*`和`operator->`。文章还讨论了在迭代器使用过程中遇到的问题,如因删除操作导致的迭代器失效及其解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

迭代器定义

迭代器(iterator):扮演容器与算法之间的胶合剂,是所谓的“泛型指针”。共有5种类型

迭代器模式:提供一种方法,使之能够依序寻访某个聚合物(容器)所含的各个元素,而又无需暴露该聚合物的内部表达方式。

STL的中心思想在于:将数据容器和算法分开,彼此独立设计,最后再以一贴胶着剂(iterator)将它们撮合在一起。

STL的迭代器是一个可遍历STL容器全部或者部分数据。

迭代器原理

迭代器是一种行为类似智能指针的对象,而指针最常见的行为就是内容提领和成员访问。因此迭代器最重要的行为就是对operator*和operator->进行重载。

 迭代器的应用

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <string>
using namespace std;
void Test1()
{
	vector<int > v1;
	v1.push_back(5);
	v1.push_back(4);
	v1.push_back(3);
	v1.push_back(2);
	v1.push_back(1);
	// 迭代器遍历顺序表
	vector<int >::iterator it = v1.begin();
	for (; it != v1.end(); ++it)
	{
		cout << *it << " ";
	}
	cout << endl;
	// STL的排序算法
	sort(v1.begin(), v1.end());
	it = v1.begin();
	for (; it != v1.end(); ++it)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void Test2()
{
	list<string > l1;
	l1.push_back("xjh");
	l1.push_back("zpw");
	l1.push_back("yb");
	l1.push_back("whb");
	// 迭代器遍历链表
	list<string >::iterator it = l1.begin();
	for (; it != l1.end(); ++it)
	{
		cout << *it << " ";
	}
	cout << endl;
	// STL的替换算法
	replace(l1.begin(), l1.end(), "xjh", "lcf");
	it = l1.begin();
	for (; it != l1.end(); ++it)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void Test3()
{
	list<string > l1;
	l1.push_back("xjh");
	l1.push_back("zpw");
	l1.push_back("yb");
	l1.push_back("whb");
	// 迭代器遍历链表
	list<string >::iterator it = l1.begin();
	for (; it != l1.end(); ++it)
	{
		cout << *it << " ";
	}
	cout << endl;
	// STL的find 算法查找迭代器区间的数据,并返回找到节点的迭代器
	it = find(l1.begin(), l1.end(), "yb");
	if (it != l1.end())
	{
		cout << "find success:" << *it << endl;
		// 通过迭代器修改节点数据
		*it = "yls
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值