国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

對std::vector/list的iterator簡單包裝嘗試

2019-11-11 03:24:16
字體:
供稿:網(wǎng)友

記錄一個對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實現(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實現(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;}


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 荥经县| 华容县| 政和县| 沾益县| 临澧县| 翼城县| 丰城市| 应城市| 高碑店市| 大渡口区| 平远县| 仁化县| 邵东县| 宝鸡市| 垦利县| 民乐县| 彭山县| 花莲市| 青川县| 尼勒克县| 汉川市| 宜章县| 昌黎县| 伊春市| 铜陵市| 吉林市| 辽阳县| 辽宁省| 漳平市| 长子县| 军事| 明溪县| 永泰县| 泽库县| 西乌珠穆沁旗| 新竹县| 汝州市| 措美县| 崇仁县| 仁寿县| 温州市|