C++标准库之迭代器

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

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

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

categorypropertiesvalid expressions
all categories copy-constructiblecopy-assignable and destructible X b(a);
b = a;
Can be incremented ++a
a++
Random Access Bidirectional Forward Input Supports equality/inequality comparisons a == b
a != b
Can be dereferenced as an rvalue *a
a->m
Output Can be dereferenced as an lvalue 
(only for mutable iterator types)
*a = t
*a++ = t
  default-constructible X 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 iterators a < 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