迭代器

    技术2022-07-10  136

    一、迭代器

    迭代器是一种类型替换,如typedef double* iterator; 每个容器类都定义了迭代器, 迭代器是一种广义指针,用来为不同的容器提供统一的接口。 举个栗子: vector ::iterator pr; 此时代表的是: double* pr; vector ::iterator pr; 此时代表的是: int* pr; 而迭代器iterator用于泛指所有类型指针。

    //声明一个迭代器 vector<double>::iterator pd; //或者 auto pd=abc.begain(); //使用迭代器 *pd=22.3; pd=abc.begain(); ++pd;

    遍历

    vector<double>::iterator pd; for(pd=abc.begain();pd !=abc.end();pd++) cout<<*pd<<endl;

    使用auto可进一步简化代码:

    for(auto pd=abc.begain();pd !=abc.end();pd++) cout<<*pd<<endl;

    二、迭代器类型

    输入和输出是相对于程序说的,输入代表读容器,输出代表写容器。

    输入迭代器:单通行,只读;输出迭代器:单通行,只写;正向迭代器:多通行,可读写,也可只读 //可读写 int* rw; //只读 const int* onlyr; 双向迭代器:包含正向迭代器特性,双向访问;随机访问迭代器:包含双向迭代器所有特性,随机访问。

    作为一种编程风格,最好直接避免使用迭代器,而是尽可能使用STL函数,如for_each.

    三、一些函数和迭代器

    可以将指针容器作为迭代器使用在函数中。

    函数作用sort(a,a+10);指定范围内排序copy(a,a+10,c.begain());将指定内容a复制到矢量c中

    将内容输出到屏幕上(cout接口):

    #include<iterator> ... ostream_iterator<int,char> out_iter(cout," "); copy(a.begain(),a.end(),out_iter());

    or

    #include<iterator> ... copy(a.begain(),a.end(),ostream_iterator<int,char>(cout," "));

    cin接口

    copy(istream_iterator<int,char>(cin),istream_iterator<int,char>,dice.begain);

    这样就可以使用键盘输入到dice容器内了。

    返回迭代器下标方法

    第一种方法

    首先介绍一个函数:distance,它返回的是两个迭代器之间的距离。

    使用这个函数,就能完成迭代器与下标之间的转换:下标 = 当前迭代器位置-容器头部

    注:在使用过程中,可以结合begin()和返回的迭代值进行求下标的计算。

    #include <iostream> #include <list> using namespace std; int main () { list<int> mylist; for (int i=0; i<10; i++) mylist.push_back (i*10); list<int>::iterator first = mylist.begin(); list<int>::iterator last = mylist.end(); list<int>::iterator it = first; for(;it != last;++it) cout<<"第"<<distance(first,it)<<"个元素的值为:"<<*it<<endl; system("pause"); return 0; 第0个元素的值为:0 第1个元素的值为:10 第2个元素的值为:20 第3个元素的值为:30 第4个元素的值为:40 第5个元素的值为:50 第6个元素的值为:60 第7个元素的值为:70 第8个元素的值为:80 第9个元素的值为:90 Press any key to continue . . .

    第二种方法

    由迭代器得到元素下标

    vector<int> temp = { 1,3,2,4,5,0 }; vector<int>::iterator it=temp.begin(); it+=2; //此时it对应的元素下标为 int index=&*it-&temp[0];
    Processed: 0.012, SQL: 9