STL中迭代器 (Iterator) 的简单实现
#pragmaoncestructInputIteratorTag{};structOutputIteratorTag{};structForwardIteratorTag:publicInputIteratorTag{};structBidirectionalIteratorTag:publicForwardIteratorTag{};structRandomAccessIteratorTag:publicBidirectionalIteratorTag{};template<classT>structInputIterator{//typedefTValueType;//typedefDistanceDifferenceType;//typedefT*Pointer;//typedefT&Reference;typedefInputIteratorTagIteratorCategory;//迭代器的类型(包括上面那5个struct)};template<classIterator>structIteratorTraits{//typedeftypenameIterator::ValueTypeValueType;//typedeftypenameIterator::DifferenceTypeDifferenceType;//typedeftypenameIterator::PointerPointer;//typedeftypenameIterator::ReferenceReference;typedeftypenameInputIterator<Iterator>::IteratorCategoryIteratorCategory;};template<classT>structIteratorTraits<T*>//内置类型的特化版本{typedefRandomAccessIteratorTagIteratorCategory;};template<classInputIterator>inlinesize_tDistance(InputIteratorfirst,InputIteratorlast){return_Distance(first,last,IteratorTraits<InputIterator>::IteratorCategory());//这里第三个参数并没有实际意义,不过正是它的存在,让_Distance实现重载}template<classInputIterator>inlinesize_t_Distance(InputIteratorfirst,InputIteratorlast,RandomAccessIteratorTag){returnlast-first;}template<classInputIterator>inlinesize_t_Distance(InputIteratorfirst,InputIteratorlast,InputIteratorTag){size_tn=0;while(first!=last){++first;++n;}returnn;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。