STL 筆記(四) 叠代器 iterator
阿新 • • 發佈:2017-08-17
mutable ssi trac 方法 iter ++ pos and 全部
stl 中叠代器能夠理解為面向對象版本號的廣義指針,提供了對容器中的對象的訪問方法,能夠遍歷容器全部元素。也能夠訪問隨意元素。stl 叠代器有下面五種:
【原文:http://blog.csdn.net/thisinnocence/article/details/39909787】
- Input iterators 僅僅讀,輸入叠代器,支持如:istream
- Output iterators 僅僅寫,輸出叠代器。支持如:ostream、inserter
- Forward iterators 讀寫,前向叠代器。僅僅能前向移動
- Bidirectional iterators 讀寫,雙向叠代器,可以雙向移動。支持如: list、set、map
- Random access iterators 讀寫,隨機叠代器,可以隨機訪問,支持如:vector、deque、string
從功能上看,輸入和輸出叠代器並列,然後前向叠代器、雙向叠代器和隨機叠代器之間的關系就類似於類的繼承關系。比方。能夠將隨機訪問叠代器作為雙向叠代器或前向叠代器來使用。
舉例:
stl 中的 find 函數須要輸入叠代器:
template <class _InputIter, class _Tp> inline _InputIter find(_InputIter __first, _InputIter __last, const _Tp& __val, input_iterator_tag) { while (__first != __last && !(*__first == __val)) ++__first; return __first; }
stl 中 的 generate_n 函數須要輸出叠代器:
/* The generate_n algorithm traverses the range [first, first + n) assigning to each element the value returned by gen. Note that generate modifies the elements in the specified range. */ template <class _OutputIter, class _Size, class _Generator> _OutputIter generate_n(_OutputIter __first, _Size __n, _Generator __gen) { __STL_REQUIRES(_OutputIter, _OutputIterator); for ( ; __n > 0; --__n, ++__first) *__first = __gen(); return __first; }
stl 中 replace 函數要求前向叠代器:
template <class _ForwardIter, class _Tp> void replace(_ForwardIter __first, _ForwardIter __last, const _Tp& __old_value, const _Tp& __new_value) { __STL_REQUIRES(_ForwardIter, _Mutable_ForwardIterator); __STL_REQUIRES_BINARY_OP(_OP_EQUAL, bool, typename iterator_traits<_ForwardIter>::value_type, _Tp); __STL_CONVERTIBLE(_Tp, typename iterator_traits<_ForwardIter>::value_type); for ( ; __first != __last; ++__first) if (*__first == __old_value) *__first = __new_value; }
stl 中的 reverse 函數要求雙向叠代器:
template <class _BidirectionalIter> inline void reverse(_BidirectionalIter __first, _BidirectionalIter __last) { __STL_REQUIRES(_BidirectionalIter, _Mutable_BidirectionalIterator); __reverse(__first, __last, __ITERATOR_CATEGORY(__first)); }
stl 中的 sort 函數要求隨機訪問叠代器:
template <class _RandomAccessIter> inline void sort(_RandomAccessIter __first, _RandomAccessIter __last) { __STL_REQUIRES(_RandomAccessIter, _Mutable_RandomAccessIterator); __STL_REQUIRES(typename iterator_traits<_RandomAccessIter>::value_type, _LessThanComparable); if (__first != __last) { __introsort_loop(__first, __last, __VALUE_TYPE(__first), __lg(__last - __first) * 2); __final_insertion_sort(__first, __last); } }
【原文:http://blog.csdn.net/thisinnocence/article/details/39909787】
STL 筆記(四) 叠代器 iterator