1.stl迭代器之配接器( Iterator Adapters)
迭代器(Iterators)是一个纯抽象的概念:任何东西,只要其行为类似迭代器,它就是一个迭代器.也就是说,只有具备有迭代器的四种基本操作:取值(*),递增(++)
比较(== !=) 赋值(=)它就是迭代器。因此,你可以自己写一些类别(classes),具备迭代器接口,但有着各不相同的行为。c++标准库中提供了数个预先定义的特需迭代器
也就是所谓的迭代器配接器(Iterator Adapters).迭代器配接器不仅起到了辅助作用,还能赋予整个迭代器抽象概念更强大的能力。
2.三种迭代器配接器(iterator Adapters)
一般包含三种迭代器:(1)insert iterators(安插型迭代器)(2)stream iterators (流迭代器)(3)reverse iterators (逆向迭代器)详细信息可参考《c++ 标准程序库》第7.4节。主要介绍安插型迭代器。
1.安插型迭代器(insert iterators)
安插型迭代器可以使算法以安插(insert)方向而非覆写(overwrite)方式运作。使用它可以解决目标空间不足问题。也就是说,安插型迭代器会促使目标区间的大小按需要增长。安插型迭代器内部将接口重新做了定义:如果你对容器中的某个数据元素设值(assign),会引发“对其所属的容器内的数据元素的安插(insert)操作”至于插入的位置是在容器的最前还是最后,或是特定的位置,它根据三种不同的安插型迭代器(insert iterators)而定。
1)back_inserter(container):使用push_back()在容器尾端安插元素,元素排列顺序和安插顺序相同。只有在提供了push_back()成员函数的容器才能使back_inserter(container)这样的容器有:vector,deque,list
2)front_inserter(container):在内部调用push_front()成员函数,将元素安插于容器中最前端。采用头插法插入元素,数据元素在容器中的位置和插入时的顺序刚好相反。同样,只有提供了push_front()成员函数的容器才能使用 front_inserter(container)这样的迭代器有:deque,list.
3)inserter(container,pos):在内部调用insert()成员函数,将元素插入第二个参数所指的位置。因为在stl所有的容器中都包含有insert()成员函数,所以所有的容器包括关联式容器都能够使用 inserter(container, pos).但是,我们知道关联式容器中数据元素是有序的,数据元素在容器中的位置只是和元素值有关。在关联式容器中,提供一个迭代器只是告诉容器确定从什么地方开始搜寻正确的位置,如果提示不正确的话,效率比没有提示更糟,所以对关联式容器来说,我们必须慎重 。
3.c++代码解释:以back_inserter()为例
#include<iostream>
#include<vector>
#include<deque>
#include<set>
#include<list>
#include<algorithm>
#include<iterator>
using namespace std;
int main( int argc ,char **argv)
{
list<int> int_list;
//insert elements from 1 to 9 into the first collection : int_list
for(int i = 1; i <= 9 ; ++i)
int_list.push_back(i);
//printf all the elements in the int_list
list<int>::iterator list_pos;
cout<<"elements in the int_list now: ";
for( list_pos = int_list.begin(); list_pos != int_list.end(); ++list_pos)
cout << *list_pos << ' ';
cout << endl;
//copy all the elements of int_list into int_vector by appending them
vector<int> int_vector;
copy(int_list.begin(),int_list.end(),back_inserter(int_vector));
//printf all the elements int the int_vector
vector<int>::iterator pos_vector;
cout<<"elements in the int_vector:";
for( pos_vector = int_vector.begin(); pos_vector != int_vector.end();++pos_vector)
cout<< *pos_vector << ' ';
cout<< endl;
//copy all the elements of int_list into int_set
//only inserter that works for associative containers
set<int> int_set;
copy(int_list.begin(),int_list.end(),inserter(int_set,int_set.begin()));
set<int>:: iterator pos_printf_list;
cout<<"elements of int_set now:";
for(pos_printf_list = int_set.begin(); pos_printf_list != int_set.end(); ++pos_printf_list)
cout<< *pos_printf_list << ' ';
cout<< endl;
return 0;
}
4.结果:
转自:https://blog.csdn.net/tianxiaolu1175/article/details/48413163