迭代器

本文深入探讨了迭代器的概念,其在STL中的角色,以及如何使用迭代器与算法进行数据查找。通过实例展示了在不同容器中使用迭代器进行元素搜索的方法。

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

迭代器的定义: 提供一种方法,使之能够巡访某个聚合物(容器)所含的各个元素,而又无需暴露该聚合物的内部表达方式
STL的中心思想是将容器和算法分开,然后用迭代器将两者联系起来
//以find为例子

template <class InputIterator ,class T>
InputIterator find(InputIterator first,InputIterator last,const T& value){
	while(first!=last&&*first!=value)
		++first;
	return first;
}

下面附上一个使用迭代器的例子

#include<vector>
#include<list>
#include<deque>
#include<algorithm>
#include<iostream>
using namespace std;
int  main(){
	const int arraySize=7;
	int ia[arraySize]={0,1,2,3,4,5,6};
	vector<int>ivect(ia,ia+arraySize);
	list<int>ilist(ia,ia+arraySize);
	deque<int>ideque(ia,ia+arraySize);
	vector<int>::iterator it1=find(ivect.begin(),ivect.end(),4);
	if(it1==ivect.end())
	cout<<"4 not found"<<endl;
	else
	cout<<"4 found"<<*it1<<endl;
	list<int>::iterator it2=find(ilist.begin(),ilist.end(),6);
	if(it2==ilist.end()){
	cout<<"6 not found"<<endl;
}else
	cout<<"6 found"<<*it2<<endl;
deque<int>::iterator it3=find(ideque.begin(),ideque.end(),8);
 if(it3==ideque.end())
	cout<<"8 not found"<<endl;
else
	cout<<"8 found "<<*it3<<endl;
return 0;
}

//给与不同的迭代器 find()测试
//原生指针 auto_ptr

void func(){
	auto_ptr<string>ps(new string("jjhou"));//以算式new动态分配一个初值为"jjhou" 并将所得的结果作为auto_ptr<string>的初值
	cout<<*ps<<endl;
	cout<<ps->size()<<endl;
	//离开前不需要delete auto_ptr自动释放内存
}

迭代器所指对象的型别,称为该迭代器的value type .但是这个value type不可用于函数的返回值.函数的"template参数推到机制"推导的只是参数,无法推导函数的返回值型别
于是我们使用函数的声明内嵌

template <class T>
struct MyITer{
typedef T value_type;//内嵌说明
T* ptr;
MyIter(T *p=0):ptr(p){}
T& operator*()const{return *ptr;}
};
template<class T>
template I::value_type//这一行是func的返回值类别
func(I ite){
	return *ite;
	}
	MyIter<int>ite(new int(8));
	cout<<func(ite);//输出是8

注意,func()的返回类别必须加上关键字typename,因为T是一个template类别的参数,在被编译器具体化之前,编译器不了解T的信息,用template的用意是在告诉编译器这是一个型别,这样才能通过编译

当遇见原生指针的时候,这种做法就会出现问题 于是引入了偏特化
用来萃取迭代器的特性

template <class I>
struct iterator_traits{
typedef typename I::value_type value_type;
};

萃取出来的value_type就是I::value_type.
那么原先的的func函数就可以这样写

template <class I>
typename iterator_traits<I>::value_type//这一整行是函数返回类别
func(I ite)
{
	return *ite;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值