您的位置:首页 > 编程语言 > C语言/C++

c++ primer第五版(中文)习题答案 第十章第四节第三小节-反向迭代器

2015-10-14 23:02 288 查看
本博客知识记录自己学习中的笔记或者记录,如果有错误欢迎大家纠正。

本节主要学习迭代器反向迭代器

学习笔记:

反向迭代器就是在容器中从尾元素向首元素反向移动的迭代器,对于方向迭代器递增递减的操作含义也会颠倒,递增一个反向迭代器(++it)会移动到前一个元素,递减一个反向迭代器(–it)会移动到下一个元素。

除了forward_list(流迭代器也不行)之外,其他容器都支持反向迭代器,rbegin rend,crbegin,crend,成员函数来获取反向迭代器.

反向迭代器的目的是表示元素范围,而这些范围是不对称的,这导致一个重要的结果:当我们从一个普通迭代器初始化一个反向迭代器,或是给一个反向迭代器赋值时,结果迭代器与原迭代器指向的并不是相同元素。

习题练习:

10.34 使用reverse_iterator逆序打印出一个vector。

#include <vector>
#include <iostream>

int main()
{

//初始化一个vector
std::vector<int>vecInt = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//使用反向迭代器 输出,
for (auto r_iter = vecInt.crbegin(); r_iter != vecInt.crend();++r_iter)
std::cout << *r_iter << " ";

std::cout << std::endl;

system("pause");
return 0;
}


输出为:



10.35使用普通迭代器逆序打印一个vector。

#include <vector>
#include <iostream>

int main()
{

std::vector<int>vecInt = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int>::iterator it = vecInt.end();
std::vector<int>::iterator it2 = vecInt.begin();

//   vector容器的end是指向最后一个元素的下一个位置,
//   使用时要将迭代器减1,才能获取到最后一个

it--; //   注意这句让迭代器正确指向有数据的尾部。
while (it!=it2) //判断是否和首部相等
{
std::cout << *it << " ";
it--;
if (it == vecInt.begin()) //如果等于首部 输出
std::cout << *it << " ";
}
std::cout << std::endl;

system("pause");
return 0;
}


输出为:



10.36:使用find在一个int的list中查找最后一个值为0的元素。

#include <list>
#include <iostream>
#include <algorithm>
int main()
{

std::list<int> listInt = { 0, 1, 2, 6, 4, 5, 9, 2, 0, 8 };

//使用反向迭代器后,返回的迭代器a也是逆序迭代器
auto a = std::find(listInt.crbegin(), listInt.crend(), 0);

std::cout << *(a);
std::cout << " the next number is " << *(--a);
//逆向迭代器使用--指向下一个。

system("pause");
return 0;
}


输出结果为:



10.37给定一个包含10个元素的vector,将位置3到位置7之间的 元素按逆序拷贝到一个list中。

#include <list>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> vecInt = { 0,1,2,3,4,5,6,7,8,9};
std::list<int> listInt;

//位置3到7逆序拷贝 注意逆向
std::copy(vecInt.rbegin() + 2, vecInt.rend() - 2, std::back_inserter(listInt));

for (auto a:listInt)
std::cout << a << " ";

system("pause");
return 0;
}


输出结果为:



习惯顺序后,逆序大意就会出错, 细心, 还有end是指向最后一个元素的下一个位置,而不是最后一个元素的位置。切记。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: