Bootstrap

std::back_inserter、std::inserter、std::front_inserter 用法

描述:
       std::back_inserter: 创建一个使用push_back的迭代器,元素总是插入到容器最后一个元素之后。
       std::inserter 此函数接受第二个参数,这个参数必须是一个指向给定容器的迭代器。元素将被插入到给定迭代器所表示的元素之前。
       std::front_inserter : 创建一个使用push_front的迭代器,元素总是插入到容器第一个元素之前。

示例:
       由于list容器类型是双向链表,支持push_front和push_back操作,因此选择list类型来试验这三个迭代器。

#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>

int main()
{
	std::list<int> v1 = {1,2,3,4 };
	std::list<int> v2 = { 5 }, v3 = { 5 }, v4 = { 5 };

	std::copy(v1.begin(),v1.end(),std::back_inserter(v2));
	std::for_each(v2.begin(), v2.end(), [](int nValue) {std::cout << nValue << ' '; });
	std::cout << std::endl;
	//5 1 2 3 4

	std::copy(v1.begin(),v1.end(),std::inserter(v3,v3.begin()));
	std::for_each(v3.begin(), v3.end(), [](int nValue) {std::cout << nValue << ' '; });
	std::cout << std::endl;
	//1 2 3 4 5

	std::copy(v1.begin(), v1.end(), std::front_inserter(v4));
	std::for_each(v4.begin(), v4.end(), [](int nValue) {std::cout << nValue << ' '; });
	std::cout << std::endl;
	//4 3 2 1 5
}
;