迭代器类似于指针但它指向的是一个容器,不是简单的类型。
迭代器包括插入迭代器,iostream迭代器,反向迭代器。其实质就是将迭代器与不同的数据类型绑定一起。分别与容器,输入输出流绑定。
下面介绍一些相关的泛型算法:
#include <iostream>
#include <algorithm> //算法头文件
#include <numeric> //算数运算
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector<int> vec;
for(int i=0; i<10; i++) {
vec.push_back(i);}
int sum = accumulate(vec.begin(),vec.end(),0); //first,end,base.
cout<<"sum:" << sum <<endl;
//查找两个容器中相同的部分
vector<int> rose(vec.begin(),vec.end());
int size = 0;
vector<int>::iterator it = vec.begin();
//每次查找第一个匹配,实质就是从vec中一个一个与rose的所有的比较,一旦匹配则返回
while((it = find_first_of(it,vec.end(),rose.begin(),rose.end()))!= vec.end()) {
it++;
size++;}
cout << "Find:"<<size <<endl; //输出的为10,每个元素都有对应的
fill(rose.begin(),rose.end(),2);//填充容器
copy(rose.begin(),rose.end(),back_inserter(vec));//rose插在vec的后边back_inserter为插入迭代器
cout << "rose sum:" << accumulate(rose.begin(),rose.end(),0) <<endl;
cout << "vec sum:" << accumulate(vec.begin(),vec.end(),0) <<endl;
replace(rose.begin(),rose.end(),2,3); //将rose中的2全部换成3
cout << "rose sum:" << accumulate(rose.begin(),rose.end(),0) <<endl;
replace_copy(rose.begin(),rose.end(),back_inserter(vec),3,2);
//将rose中的3全部换成2,并保存在副本vec中。这里不能replace_copy(rose.begin(),rose.end(),back_inserter(rose),3,2);
//因为这里replace函数实际是一个循环的过程,如果对rose操作,那么rose.end()就会发生改变……
cout << "rose vec:" << accumulate(vec.begin(),vec.end(),0) <<endl;
//流迭代器
vector<int> is;
istream_iterator<int> in_iter(cin); //以int数据读出放入is中
istream_iterator<int> eof;
while(in_iter != eof) {
is.push_back(*in_iter++);
}
cout << *(is.begin()+1)<< endl;
return 0;
}