STL迭代器(iterator)简要
迭代器(iterator)类似于指针,能够通过它访问到它所指的元素。每个容器都有一些基本的函数让你能够获得迭代器并访问容器里的元素。begin() 返回容器中第一个元素的迭代器;end() 返回容器中最后一个元素所在位置的下一个位置而不是最后一个元素的位置。另外关于迭代器 ++pos、pos++两者的效率问题中第一个操作的效率更高因为后者需要创建一个临时对象来返回结果。说明代码:
Operator Operator::operator++()
{
++value; //内部成员变量
return *this;
}
Operator Operator::operator++(int )
{
Operator temp;
temp.value=value;
value++;
return temp;
}
顺序容器操作实例
iterator操作基本实例(g++ 4.8调试通过):
#include <iostream>
using namespace std;
int main(){
list<char> temp;
for(char c='a'; c<='z';++c){
temp.push_back(c);
}
//iterator task
for(list<char>::iterator pos=temp.begin();pos!=temp.end();++pos){
cout<<*pos;
}
cout<<endl;
//const_iterator task
for(list<char>::const_iterator pos=temp.begin();pos!=temp.end();++pos){
cout<<*pos;
}
cout<<endl;
//auto iterator since c++11
for(auto pos=temp.begin();pos!=temp.end();++pos){
cout<<*pos<<" ";
}
cout<<endl;
//auto const_iterator since c++11
for(auto pos=temp.cbegin();pos!=temp.cend();++pos){
cout<<*pos<<" ";
}
cout<<endl;
}
如上所示iterator的基本类型有两种iterator与const_iterator前者对于容器的元素可读可写,而后者只能读而不能修改元素的值。而auto操作符是c++11标准加入的,它的优势可以很明显的看出来,首先声明简单明了,而且如果更改容器的类型,声明语句不需要做修改,而在原先的标准下的声明则要修改。
关联容器操作实例:
#include<iostream>
using namespace std;
int main(){
typedef set<int> IntSet;
IntSet temp;
temp.insert(1);
temp.insert(2);
temp.insert(3);
temp.insert(4);
temp.insert(5);
temp.insert(6);
//print all elem
for(auto pos=temp.cbegin();pos!=temp.cend();++pos){
cout<<*pos<<" ";
}
cout<<endl;
//task2
temp.clear();
temp.insert({3,1,5,4,1,6,2});//since c++11
for(auto pos=temp.cbegin();pos!=temp.cend();++pos){
cout<<*pos<<" ";
}
cout<<endl;
}
输出的结果都是:
1 2 3 4 5 6
上面例子表明关联容器的迭代器与插入的时间无关只与插入的值有关而且set容器不被允许有相同值(相同值只显示一个,要是需要相同值都可以使用 multiset )。该例中插入的数字可以用二叉排序树的形式来理解,顺序输出的形式是二叉树的中序输出。