一、reverse(逆向)迭代器
rbegin()传回逆向遍历的第一元素位置,也就是实际上最后一个元素的位置
rend()传回逆向遍历时最后一个元素的下一位置,也就是实际上第一元素的前一个位置。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> coll;
// insert elements from 1 to 9
for (int i=1; i<=9; ++i) {
coll.push_back(i);
}
// find position of element with value 5
vector<int>::iterator pos;
pos = find (coll.begin(), coll.end(),
5);
// print value to which iterator pos refers
cout << "pos: " << *pos << endl;
// convert iterator to reverse iterator rpos
vector<int>::reverse_iterator rpos(pos);
// print value to which reverse iterator rpos refers
cout << "rpos: " << *rpos << endl;
}
运行结果:
pos: 5
rpos: 4
请按任意键继续. . .
将一个迭代器转换为逆向迭代器的过程中保持(履行)的是实际位置(元素)而非逻辑位置(数值)
以base()将逆向迭代器转回正常迭代器
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
list<int> coll;
// insert elements from 1 to 9
for (int i=1; i<=9; ++i) {
coll.push_back(i);
}
// find position of element with value 5
list<int>::iterator pos;
pos = find (coll.begin(), coll.end(), // range
5); // value
// print value of the element
cout << "pos: " << *pos << endl;
// convert iterator to reverse iterator
list<int>::reverse_iterator rpos(pos);
// print value of the element to which the reverse iterator refers
cout << "rpos: " << *rpos << endl;
// convert reverse iterator back to normal iterator
list<int>::iterator rrpos;
rrpos = rpos.base();
// print value of the element to which the normal iterator refers
cout << "rrpos: " << *rrpos << endl;
}
运行结果:
pos: 5
rpos: 4
rrpos: 5
请按任意键继续. . .
1.push_back(value)只存在于vector、deque、list、string中,将一个元素追加于容器尾部
2.push_front(value)只存在于deque、list中,将一个元素追加于容器头部
3.insert(pos,value)使用于所有容器,只不过对于关联式容器(set,map)而言,安插位置只是个提示,因为在这两种容器中,元素的真正位置视其实值(或键值)
三、stream流迭代器