記錄一個(gè)對iterator的定義嘗試:
1. 使用typename定義直接推導(dǎo)最簡單
2. 使用iterator的基礎(chǔ)類型比較麻煩(使用allocator、std::iterator基礎(chǔ)定義),需要再深入看下stl源碼解析。
#include <vector>#include <list>#include <iostream>template <typename _Tp>class PackIntsVector{public: // 賦值走copy構(gòu)造 PackIntsVector(const std::vector<_Tp>& vec) { m_vecInts = vec; }; // vector::iterator實(shí)現(xiàn) // 方法一:遍歷類型指定: std::forward_iterator_tag,iterator的原始結(jié)構(gòu)體類型:不支持++, --, !=等操作 // typedef std::iterator<std::forward_iterator_tag, _Tp, __int64, _Tp*, _Tp&> iterator; // 方法二:分配類型指定:std::allocator<_Tp>, 并包裝iterator, 提供++,--,!=等方法 // 指定分配類型:std::allocator<_Tp> // typedef typename __gnu_cxx::__alloc_traits< std::allocator<_Tp> >::template rebind<_Tp>::other _Tp_alloc_type; typedef typename std::allocator<_Tp> _Tp_alloc_type; // 獲取元素指針類型 // typedef typename __gnu_cxx::__alloc_traits<_Tp_alloc_type>::pointer pointer; typedef typename _Tp_alloc_type::pointer pointer; // 初始化iterator,提供了*, ->, !=, +=, -= 等方法 typedef __gnu_cxx::__normal_iterator<pointer, std::vector<_Tp> > iterator; // 方法三:等效于下面這句話 (注意,必須有typename關(guān)鍵字說明,用于告訴編譯器推導(dǎo)) // typedef typename std::vector<_Tp>::iterator iterator; iterator begin() { return m_vecInts.begin(); }; iterator end() { return m_vecInts.end(); }; // list::iterator實(shí)現(xiàn) // 方法一: typedef typename std::_List_iterator<_Tp> iteratorLst; // 方法二: //typedef typename std::list<_Tp>::iterator iteratorLst; iteratorLst beginLst() { return m_lstInts.begin(); }; iteratorLst endLst() { return m_lstInts.begin(); };PRivate: std::vector<_Tp> m_vecInts; std::list<_Tp> m_lstInts;};int main(){ std::vector<int> vecInts; for (int i=0; i<10; ++i) { vecInts.push_back(i); } PackIntsVector<int> pack = vecInts; for (PackIntsVector<int>::iterator iter = pack.begin(); iter != pack.end(); ++iter) { std::cout << *iter << std::endl; } for (PackIntsVector<int>::iteratorLst iter = pack.beginLst(); iter != pack.endLst(); ++iter) { std::cout << *iter << std::endl; } return 1;}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注