STL讀書筆記— 迭代器概念

來源:互聯網
上載者:User

一。概念

1)迭代器在設計模式中成為iterator模式,其定義為:提供一種方法,使他能夠按順序遍曆某個彙總體(容器)所包含的所有元素,但又不需要暴露該容器的內部表現方式。

2)迭代器是一種類似指標的對象,他的工作也主要是內容提取(dereference)和成員的訪問(member access)。因此其對應的兩個重載操作符工作是:operator*和operator-> 。

二。常用迭代器類型

最常用的迭代器類型包括:value type, difference type, pointer, reference, iterator catagoly.

1)value type,是指迭代器所指對象的類型。

2)difference type,用來表示兩個迭代器之間的距離,也可以表示一個容器的最大值。

3)reference type,意為迭代器所指之物的內容。在C++中如果函數要傳回左值,都是以by reference的方式進行的。

4)pointer type,指向迭代器所指之物。在C++中,可以實現傳回一個左值,令他代表pointer所指之物的地址。

5)iterator_category,表示迭代器的相應類型。在這之前,討論迭代起器的分類:

      a. input iterator:該迭代器所指的對象不允許被外部改變,read only。

      b. output iterator:只允許寫操作,write only。

      c. forward iterator:允許“寫入型”的演算法在此迭代器內進行讀寫操作。

      d. bidirectional iterator:提供雙向移動操作。

      e. random access iterator: 增加指標算術能力。例如 ptr+n, ptr[n], ptr1-ptr2, ptr1<ptr2。

三。迭代器定義源碼

 

//五種迭代器類型struct input_iterator_tag {};struct output_iterator_tag {};struct forward_iterator_tag : public input_iterator_tag {};struct bidirectional_iterator_tag : public forward_iterator_tag {};struct random_access_iterator_iterator_tag : public bidirectional_iterator_tag {};//std::iterator.自訂的迭代器應當繼承下面這個iteratortemplate <class Category,   class T,  class Distance = ptrdiff_t,  class Pointer = T*,  class Reference = T&>struct iterator{typedef Category  iterator_category;typedef T         value_type;typedef Distance  difference_type;typedef Pointer   pointer;typedef Reference reference;};//特性萃取,擷取各個迭代器的相應類型template <class Iterator>struct iterator_traits{typedef typename Iterator::iterator_category iterator_category;typedef typename Iterator::value_type        value_type;typedef typename Iterator::difference_type   difference_type;typedef typename Iterator::pointer           pointer;typedef typename Iterator::reference         reference;};

參考資料:《STL源碼剖析》華中科大出版社

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.