zl程序教程

您现在的位置是:首页 >  其他

当前栏目

插入迭代器

2023-03-14 22:51:00 时间

定义:

  • 插入迭代器是一种迭代器适配器,它接受一个容器,生成一个迭代器,能实现向给定容器添加元素。
  • 其实适配器的本质就是实现不变,改变接口。
  • 例如容器适配器可以使一个容器vector表现得像一个stack一样,这里的迭代器适配器也是如此。

插入器有三种类型,差异在于元素插入的位置:

  • back_inserter 创建一个使用push_back的迭代器。
  • front_inserter 创建一个使用push_front的迭代器。
  • inserter 创建一个使用insert的迭代器。

假设iter是一个插入迭代器,则

  • iter = val;
  • 在iter指定的当前位置插入值val。
  • 假定c是it绑定的容器,依赖于插入迭代器的不同种类,此赋值会分别调用c.push_back(val)、c.push_front(val)或c.inserter(iter,pos),其中pos为传递给inserter的迭代器位置
  • *iter,++iter,iter++
  • 这些操作虽然存在,但不会对iter做任何事情,每个操作都返回iter

tips: 只有在容器支持push_front的情况下,才能使用front_inserter。同样,只有容器支持push_back的情况下,才能使用back_inserter。

代码演示:

#include<iostream>
#include<list>
#include<algorithm>
using namespace std;
void test()
{
	list<int> lst = { 1,2,3,4 };
	list<int> lst1, lst2;
	auto iter_back = back_inserter(lst1);
	auto iter_front = front_inserter(lst2);
	//写法1:
	*iter_back = 520;//等价于lst1.push_back(520)
	cout << lst1.front() << endl;
	lst1.pop_front();
	//写法2:
	iter_back = 521;//等价于lst1.push_back(521)
	cout << lst1.front() << endl;
	//注意:写法1和写法2等价的原因是*it,++it和it++不会对it做任何事情

    //下面统一用写法2:
	//注意:我们使用front_inserter总是插入到容器第一个元素之前
	iter_front = 1;
	iter_front = 2;
	iter_front = 3;
	for_each(lst2.begin(), lst2.end(), [](int val) {cout << val << " "; });
	cout << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

结合copy算法演示

  • copy算法并不检查目的序列,所以使用前务必保证目的序列大小不小于输入序列
  • 重点来了,使用插入器则不用考虑目的序列与输入序列的大小关系
#include<iostream>
#include<list>
#include<algorithm>
using namespace std;
void test()
{
	list<int> lst = { 1,2,3,4 };
	list<int> lst1, lst2;
	auto iter_back = back_inserter(lst1);
	auto iter_front = front_inserter(lst2);
	lst1.push_back(520);
	lst2.push_back(520);
	copy(lst.begin(), lst.end(), iter_back);
	copy(lst.begin(), lst.end(), iter_front);
	cout << "调用iter_back后lst1=   ";
	for_each(lst1.begin(), lst1.end(), [](int val) {cout << val << " "; });
	cout << endl;
	cout << "调用iter_front后lst2=   ";
	for_each(lst2.begin(), lst2.end(), [](int val) {cout << val << " "; });
	cout << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}