迭代器

 迭代器类似于指针但它指向的是一个容器,不是简单的类型。

迭代器包括插入迭代器,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;
}



 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值