迭代器

来源:互联网 发布:易拉宝用什么软件制作 编辑:程序博客网 时间:2024/05/14 14:26

迭代器:用来遍历容器的接口

看代码:

#include<iostream>#inlcude<vector>using namespace std;int main(){     string s("haha");     auto it=s.begin();     while(it!=s.end())//如果你不用it变量,而直接把条件写成s.begin()!=s.end(),这样就错了,因为it++了,s.begin()还是不会变,他总是指向是一个固定的位置,只能用it代替,s.begin()!=s.end()是用来判断是否为空的     {           cout<<*it<<endl;           it++;     }     /*for(auto it=s.begin();it!=end()&&!isspace(*it);++it)        {               cout<<*it<<endl;        }*/        return 0;}

打印:h

            a

            h

            a

begin ()返回第一个元素的迭代器,end()返回最后一个元素的下一个位置(根本不存在,知识做个标记),称为尾后迭代器。

上述代码中,注释部分的for循环也可以遍历容器中的元素,可以任选一种,isspace()函数判断是否为空。


迭代器分两种类型:iterator 和 const_iterator  

vector<int>::iterator v;//里面的元素能读写vector<int>::const_iterator v1;//里面的元素只能读string::iterator s;//能读写string::const_iterator;//能读不能写

迭代器中也定义了'->'运算符,'->'把解引用和'.'元素符代替了

#include<iostream>#include<string>using namespace std;int main(){    vector<string> s{"haha"};//关于这里用->运算符,vector可以用,string不能用,不知为何        for(auto it=s.begin();it!=s.end()&& !it->empty();it++)//这里用到了->运算符    {              cout<<*it<<endl;    }     return 0;}




迭代器运算:能对迭代器进行算术运算

#include<iostream>#include<srting>using namespace std;int main(){     string s("woaini");     auto it=s.begin();     it=it+4;     while(it!=s.end())     {            cout<<*it<<endl;            it++:     }      return 0;      }
打印:n

             i






0 0
原创粉丝点击