C++标准库之迭代器

迭代器是对指针进行进一步抽象的产物。

迭代器是遍历所有容器(序列)/流的统一界面,是标准库泛形算法的基础。

迭代器根据其能力分为五种:

 

categorypropertiesvalid expressions
all categoriescopy-constructiblecopy-assignable and destructibleX b(a);
b = a;
Can be incremented++a
a++
Random AccessBidirectionalForwardInputSupports equality/inequality comparisonsa == b
a != b
Can be dereferenced as an rvalue*a
a->m
OutputCan be dereferenced as an lvalue 
(only for mutable iterator types)
*a = t
*a++ = t
 default-constructibleX a;
X()

Multi-pass: neither dereferencing nor incrementing affects dereferenceability

Multi-pass是指,迭代器不管进行多少次自增及解引用,都不会使得其指过的对象无法访问。

{ b=a; *a++; *b; }
 Can be decremented--a
a--
*a--
 Supports arithmetic operators + and -a + n
n + a
a - n
a - b
Supports inequality comparisons (<><= and >=) between iteratorsa < b
a > b
a <= b
a >= b
Supports compound assignment operations += and -=a += n
a -= n
Supports offset dereference operator ([])a[n]

辅助函数

template <class InputIterator, class Distance>
void advance (InputIterator& it, Distance n);

   it跳转到与原始指向相隔n的另一个元素。it为双向迭代器、随机访问的情况下n可以为负数,否则n只能为正数。表示的概念为it+=n

template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance (InputIterator first, InputIterator last);

  计算 first 与 last 之间的迭代器个数

template <class BidirectionalIterator>
BidirectionalIterator prev (BidirectionalIterator it,
typename iterator_traits<BidirectionalIterator>::difference_type n = 1);

  表示的概念为 it - n

template <class ForwardIterator>
ForwardIterator next (ForwardIterator it,
typename iterator_traits<ForwardIterator>::difference_type n = 1);

  表示的概念为 it + n

迭代器产生器

template <class Container>
back_insert_iterator<Container> back_inserter (Container& x);

  生成输出迭代器,*it = x 调用Container.push_back(x)实现

template <class Container>
front_insert_iterator<Container> front_inserter (Container& x);

  生成输出迭代器,*it = x 调用Container.push_front(x) 实现

template <class Container>
insert_iterator<Container> inserter (Container& x, typename Container::iterator it);

  生成输出迭代器,*it = x 调用Container.insert(it,x)实现

迭代器适配器,将迭代器包装成move_iterator

template <class Iterator>
move_iterator<Iterator> make_move_iterator (Iterator it);

  生成输入迭代器,将迭代器包装成move_iterator。*it = std::move(*it)

template <class OutputIterator, class T>
class raw_storage_iterator;

  将未初始化的内存包装成输出迭代器,使其可以像已经初始化的内存一样调用 *it=x

获取迭代器属性

  iterator_traits<iter>::value_type

  iterator_traits<iter>::reference

  iterator_traits<iter>::pointer

  iterator_traits<iter>::difference_type

  iterator_traits<iter>::iterator_category

 

转载于:https://www.cnblogs.com/vsuu/p/4314427.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值