本博客知识记录自己学习中的笔记或者记录,如果有错误欢迎大家纠正。
本节主要学习迭代器
学习笔记:
在标准库头文件中iterator中还定义了额外的几种迭代器
1.插入迭代器(inser iterator):这些迭代器被绑定到一个容器上,可用来向容器插入元素
2.流迭代器(stream iterator):这些迭代器被绑定到输入或输出流上,可用来遍历所关联的IO流
3.方向迭代器(reverse iterator):这些迭代器向后而不是向前移动,除了forward_list之外的标准库容器都有方向迭代器
4.移动迭代器(move iterator):这些专门的迭代器不是拷贝其中的元素,而是移动它们。
插入迭代器:接受一个容器,生成一个迭代器,能实现向给定容器中添加元素,当我们通过插入迭代器进行赋值时,该迭代器调用容器操作来向给定的容器的指定位置插入一个元素。
插入迭代器支持的操作:
it = t; 在it指定的当前位置插入t,假定c是it绑定的容器,依赖于插入迭代器的不同种类,此赋值分别调用c.push_back(t),c.push_front(t),或c.insert(t,p),其中p为传递给inserter的迭代器位置。
*it,++it,it++ 这些操作虽然存在,但不会对it做任何事情,每个操作返回it。
插入器有三种,差异在于插入的位置
back_inserter 尾部插入 需要支持 push_back才可以用
front_inserter 首部插入 需要支持 push_front才可以用
inserter 接受第二个参数 ,第二个参数必须指定给定容器的迭代器,元素被插入到给定迭代器所表示的元素之前。
习题练习:
10.26解释三种插入器的不同之处
插入位置不同。
back_inserter插入容器尾部,需要容器支持push_back操作,才能使用
front_inserter插入容器首部,需要容器支持front_inserter操作,才能使用
inserter 插入指定迭代器所代表的元素前面,元素固定,位置不固定
10.27除了用unique(参见10.2.3)之外,标准库还定义了名为unique_copy的函数,它接受第三个迭代器,表示不重复元素的目的位置,编写一个程序使用unique_copy将vector中不重复的元素拷贝到一个初始为空的list中。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <list>
int main()
{
std::vector<std::string>vecString;
std::string s = "";
std::list<std::string>listString;
while (std::cin >> s)
{
vecString.push_back(s);
}
//在复制之前要排序,不然得不到正确结果,unique和相邻比较
sort(vecString.begin(), vecString.end());
//使用插入器,来插入元素
unique_copy(vecString.begin(), vecString.end(), back_inserter(listString));
//输出list容器所有值
for(auto a :listString)
{
std::cout << a << " ";
}
system("pause");
return 0;
}
输出结果为
10.28 一个vector中保存1和9,将其拷贝到三个容器中,分别使用inserter ,back_inserter 和front_inserter将元素添加到三个容器中,对每种inserter,估计输出序列是怎样的,运行程序验证你的估计是否正确。
#include <iostream>
#include <vector>
#include <string>
#include <list>
int main()
{
std::vector<int>vecInt;
std::vector<int>vecIntOne;
std::vector<int>vecIntTwo;
std::list<int>vecIntThree;
std::list<int>listIntThree;
for (int i = 1; i < 10; i++)
vecInt.push_back(i);
copy(vecInt.begin(), vecInt.end(), inserter(vecIntOne, vecIntOne.begin()));// 顺序为 123456789
//copy(vecInt.begin(), vecInt.end(), inserter(vecIntOne,vecIntOne.end()));// 顺序为 123456789
copy(vecInt.begin(),vecInt.end(),back_inserter(vecIntTwo));//顺序为123456789
//copy(vecInt.begin(), vecInt.end(), front_inserter(vecIntThree));//顺序为987654321
copy(vecInt.begin(), vecInt.end(), back_inserter(listIntThree));//顺序为123456789
//因为在vector不存在push_front 所以不能使用vector来操作
//copy(vecInt.begin(), vecInt.end(), front_inserter(vecIntThree));//
std::cout << std::endl << "vecIntOne is : ";
for (auto one : vecIntOne)
std::cout << one << " ";
std::cout << std::endl << "vecIntTwo is : ";
for (auto two : vecIntTwo)
std::cout << two << " ";
std::cout << std::endl << "vecIntThree is : ";
for (auto three : listIntThree)
std::cout << three << " ";
system("pause");
return 0;
}
输出结果为: