#include<iostream>#include<vector>intmain(){std::vector<int>vect;for(intcount=0;count<6;++count)vect.push_back(count);std::vector<int>::const_iteratorit;// 声明一个只读迭代器it=vect.cbegin();// 将迭代器赋值为 vector 的起点while(it!=vect.cend())// 如果 it 还没有到达容器的末尾{std::cout<<*it<<' ';// 打印 it 所指的元素++it;// 移动到下一个元素}std::cout<<'\n';}
打印结果为:
1
0 1 2 3 4 5
遍历列表
遍历列表也是类似的:
1 2 3 4 5 6 7 8 91011121314151617181920
#include<iostream>#include<list>intmain(){std::list<int>li;for(intcount=0;count<6;++count)li.push_back(count);std::list<int>::const_iteratorit;// declare an iteratorit=li.cbegin();// assign it to the start of the listwhile(it!=li.cend())// while it hasn't reach the end{std::cout<<*it<<' ';// print the value of the element it points to++it;// and iterate to the next element}std::cout<<'\n';}
打印结果为:
1
0 1 2 3 4 5
可以看到,尽管 vector 和链表的具体实现截然不同,但是遍历它们的代码却几乎完全一样!
遍历集合
在这个例子中,我们首先创建一个包含6个数的集合,然后再使用迭代器依次打印它们:
1 2 3 4 5 6 7 8 91011121314151617181920212223
#include<iostream>#include<set>intmain(){std::set<int>myset;myset.insert(7);myset.insert(2);myset.insert(-6);myset.insert(8);myset.insert(1);myset.insert(-4);std::set<int>::const_iteratorit;// declare an iteratorit=myset.cbegin();// assign it to the start of the setwhile(it!=myset.cend())// while it hasn't reach the end{std::cout<<*it<<' ';// print the value of the element it points to++it;// and iterate to the next element}std::cout<<'\n';}
#include<iostream>#include<map>#include<string>intmain(){std::map<int,std::string>mymap;mymap.insert(std::make_pair(4,"apple"));mymap.insert(std::make_pair(2,"orange"));mymap.insert(std::make_pair(1,"banana"));mymap.insert(std::make_pair(3,"grapes"));mymap.insert(std::make_pair(6,"mango"));mymap.insert(std::make_pair(5,"peach"));autoit{mymap.cbegin()};// declare a const iterator and assign to start of vectorwhile(it!=mymap.cend())// while it hasn't reach the end{std::cout<<it->first<<'='<<it->second<<' ';// the value of the element it points to++it;// and iterate to the next element}std::cout<<'\n';}