C++ - 迭代器
一、迭代器:
1、定义:一个可以标识序列中元素的对象; 序列可由一对迭代器表示,一个描述其首元素,另一个描述超出序列末端一个位置的元素;
2、作用:利用迭代器可以实现代码(算法)与数据的连接;
使用方:不需知道存储和访问数据的具体细节,只需对迭代器有一定了解;
数据提供方:不需为不同用户编写代码,只需为数据配备合适的迭代器;
3、标准迭代器基础操作:
p == q //当且仅当p和q指向序列中的同一个元素或都指向序列末端元素之后时为真
p != q // !( p==q)
val = *p //对p所指向的元素进行读操作
*p = val //对p所指向的元素进行写操作
p++ //使p指向序列中的下一个元素或序列末端元素之后
4、示例:
template<class Iterator>
Iterator high(Iterator first,Iterator last)
//return an iterator to the element in [first,last) that has the highest value
{
Iterator high=first;
for(Iterator p=first;p!=last;p++){
if(*high<*p)
high=p;
}
return high;
}
int count(string& s,char c){
int n=0;
string::const_iterator i=find(s.begin(),s.end(),c);
while(i!=s.end()){
i=find(++i,s.end(),c);
n++;
}
return n;
}
浙公网安备 33010602011771号