【C++ Primer】【学习笔记】【第九章】顺序容器之:迭代器和迭代器范围

一、所有标准库容器都可以使用的迭代器运算
所有标准库容器都支持的迭代器运算
说明
*iter
返回迭代器iter所指向的元素的引用
iter->mem
获取指定元素中名为mem的成员,等效于(*iter).mem
++iter
iter++
使iter指向容器里的下一个元素
--iter
iter--
使iter指向容器里的前一个元素
iter1 == iter2
iter1 != iter2
当两个迭代器都指向同一个容器的同一个元素或者同一个容器的超出末端的下一个位置时,两个迭代器相等;否则,两个迭代器不相等。

二、vector和deque类型容器支持的迭代器运算
vector和deque标准库容器支持的迭代器运算
说明
iter + n
iter - n
使iter指向容器里的前面或后面的第n个元素
iter1 += iter2
iter1 -= iter2
iter1 - iter2
迭代器的复合赋值运算以及减法运算
>, >=, <, <=
迭代器的关系操作符

习题9.9:将list容器中的元素进行反向输出

#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <list>
#include <map>
using namespace std;

int main()
{
    int ia[5] = {0, 1, 2, 3, 4};
    int num = sizeof(ia) / sizeof(int);

    list<int> ilist(ia, ia + num);
   
    for (list<int>::iterator iter = ilist.end(); iter != ilist.begin();)
    {
        printf("%d\n", *(--iter));
    }

    return 0;
}
[chapter9]$ ./a.out
4
3
2
1
0


习题9.12:使用迭代器查找一个元素在容器中是否存在

#include <iostream> 
#include <string>
#include <utility>
#include <vector>
#include <list>
#include <map>
using namespace std;

// find ival between beg and end
// if find, return true; if not find, return false;
bool find_int(vector<int>::iterator beg, vector<int>::iterator end, int ival)
{
    while (beg != end)
    {
        if (*beg++ == ival) return true;
    }
        
    return false;
}

int main()
{
    int ia[5] = {0, 1, 2, 3, 4};
    int num = sizeof(ia) / sizeof(int);

    vector<int> ivec(ia, ia + num);
    
    for (int i = 0; i < 10; i++)
    {
        bool bool_val = find_int(ivec.begin(), ivec.end(), i);
        printf("The result of find %d is: %s.\n", i, (bool_val == true) ? "true" : "false");
    }

    return 0;
}
[chapter9]$ ./a.out 
The result of find 0 is: true.
The result of find 1 is: true.
The result of find 2 is: true.
The result of find 3 is: true.
The result of find 4 is: true.
The result of find 5 is: false.
The result of find 6 is: false.
The result of find 7 is: false.
The result of find 8 is: false.
The result of find 9 is: false.


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值