size_type ;无符号整形,足够大存储容器数据。
iterator
const_iterator
reverse_iterator iterator that addresses elements in reverse order
const_reverse_iterator
我们可以有2中方法将vector中的元素反序输出:
#include<iostream> #include<vector> using namespace std; int main() { int a[]={1,2,3}; vector<int> vec(a,a+sizeof(a)/sizeof(int)); for(vector<int>::reverse_iterator it=vec.rbegin();it!=vec.rend();it++) cout<<*it<<ends; cout<<endl; for(vector<int>::iterator it=vec.end()-1;it>=vec.begin();it--) { cout<<*it<<ends; if(it==vec.begin()) break; } cout<<endl; }
注意r.begin()返回的类型是reverse_iterator,it为++,跟正向操作相同,向前++。
还有一点注意的是当it==vec.begin()一定要退出,否则会产生错误//vector iterator not decremental ,vec.begin()不能再减了。
上面的程序可以用2句代码搞定:
for_each(vec.begin(),vec.end(),[](int i) {cout<<i<<ends; } );
for_each(vec.rbegin(),vec.rend(),[](int i){cout<<i<<ends;});
迭代器(iterator)转逆向迭代器(reverse_iterator),只需要把迭代器转入逆向迭代器的构造函数即可;逆向迭代器转迭代器,调用逆向迭代器的base成员函数即可
#include <iostream> #include <list> #include <iterator> #include <algorithm> using namespace std; int main() { list<int> coll; for(int i = 1; i <= 9; ++i) { coll.push_back(i); } list<int>::iterator pos; pos = find(coll.begin(), coll.end(), 5); cout << "pos: " << *pos << endl; list<int>::reverse_iterator rpos(pos); cout << "rpos: " << *rpos << endl; list<int>::iterator rrpos; rrpos = rpos.base(); cout << "rrpos: " << *rrpos << endl; return 0; }
difference_type signed integral type large enough to hold the difference,可能为负.
还有常见的几种类型:
value_type 元素类型 element type
reference element's lvalue type;synonym for value_type &
const_reference element's cosnt lvalue type;same as const value_type&