温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

STL中迭代器 (Iterator) 的简单实现

发布时间:2020-08-02 21:47:53 来源:网络 阅读:521 作者:shangluyi 栏目:编程语言

 

 

 

#pragma once
struct InputIteratorTag {};
struct OutputIteratorTag {};
struct ForwardIteratorTag : public InputIteratorTag {};
struct BidirectionalIteratorTag : public ForwardIteratorTag {};
struct RandomAccessIteratorTag : public BidirectionalIteratorTag {};
template<class T> 
struct InputIterator
{
 //typedef T                  ValueType;
 //typedef Distance           DifferenceType;
 //typedef T*                 Pointer;
 //typedef T&                 Reference;
 typedef InputIteratorTag IteratorCategory; //迭代器的类型 ( 包括上面那5个struct )
};
template<class Iterator>
struct IteratorTraits
{
 //typedef typename Iterator::ValueType ValueType;
 //typedef typename Iterator::DifferenceType DifferenceType;
 //typedef typename Iterator::Pointer Pointer;
 //typedef typename Iterator::Reference Reference;
 typedef typename InputIterator<Iterator>::IteratorCategory IteratorCategory;
};
template<class T>
struct IteratorTraits<T*>  //内置类型的特化版本
{
 typedef RandomAccessIteratorTag IteratorCategory;
};
template <class InputIterator>
inline size_t Distance(InputIterator first, InputIterator last)
{
 return _Distance(first, last, IteratorTraits<InputIterator>::IteratorCategory() );  //这里第三个参数 并没有实际意义,不过正是它的存在,让_Distance实现重载
}
template <class InputIterator>
inline size_t _Distance(InputIterator first, InputIterator last, RandomAccessIteratorTag)
{
 return last - first;
}
template <class InputIterator>
inline size_t _Distance(InputIterator first, InputIterator last, InputIteratorTag)
{
 size_t n = 0;
 while (first != last)
 {
  ++first;
  ++n;
 }
 return n;
}

 

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI