溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

STL中迭代器 (Iterator) 的簡單實現(xiàn)

發(fā)布時間:2020-08-02 21:47:53 來源:網(wǎng)絡 閱讀:527 作者: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*>  //內(nèi)置類型的特化版本
{
 typedef RandomAccessIteratorTag IteratorCategory;
};
template <class InputIterator>
inline size_t Distance(InputIterator first, InputIterator last)
{
 return _Distance(first, last, IteratorTraits<InputIterator>::IteratorCategory() );  //這里第三個參數(shù) 并沒有實際意義,不過正是它的存在,讓_Distance實現(xiàn)重載
}
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問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI