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

本博客知识记录自己学习中的笔记或者记录,如果有错误欢迎大家纠正。
本节主要学习迭代器反向迭代器

学习笔记:

反向迭代器就是在容器中从尾元素向首元素反向移动的迭代器,对于方向迭代器递增递减的操作含义也会颠倒,递增一个反向迭代器(++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是指向最后一个元素的下一个位置,而不是最后一个元素的位置。切记。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值