插入迭代器

C++提供了三种插入迭代器:

(1)back_inserter,创建使用push_back实现的迭代器

 (2)front_inserter,使用push_front实现(当前容器必须提供push_front操作!!!)

(3)inserter,使用insert实现插入操作。除了所关联的容器外,还带有第二个实参,指向插入起始位置的实参。


实例:

#include<list>
#include<algorithm>
#include<iterator>
#include<iostream>
using  namespace std;

int main()
{
	list<int> ilist, ilist2, ilist3;
	//ilist contains:3 2 1 0
	for (list<int>::size_type i = 0; i != 4; ++i)
		ilist.push_front(i);
	//ilist2 contains:0 1 2 3
	copy(ilist.begin(),ilist.end(),front_inserter(ilist2));
	//ilist3 contains:3 2 1 0
	copy(ilist.begin(),ilist.end(),inserter(ilist3,ilist3.begin()));

	cout << "ilist   " << "ilist2   " << "ilist3" << endl;
	for (list<int>::iterator it1 = ilist.begin(), it2 = ilist2.begin(), it3 = ilist3.begin(); it1 != ilist.end() && it2 != ilist2.end() 
		&& it3 != ilist3.end(); ++it1, ++it2, ++it3)
	{
		cout <<" "<< *it1 <<"       "<< *it2 <<"        "<< *it3 << endl;
	}
	copy(ilist2.begin(),ilist2.end(),inserter(ilist3,ilist3.begin()));
	cout << "ilist3:";
	for (list<int>::iterator it = ilist3.begin(); it != ilist3.end(); ++it)
		cout << *it << "    ";
	cout << endl;
	return 0;
}

测试结果:

插入迭代器_第1张图片

你可能感兴趣的:(迭代器,STL,插入迭代器)