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

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

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

2019-11-11 04:36:53
字體:
供稿:網(wǎng)友

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


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 铜陵市| 磐石市| 鹤壁市| 横山县| 固安县| 保靖县| 兴文县| 永丰县| 夏邑县| 涞源县| 多伦县| 武强县| 丹江口市| 甘肃省| 新津县| 紫金县| 郁南县| 峨边| 万荣县| 波密县| 平遥县| 中西区| 左权县| 富顺县| 佛坪县| 宝兴县| 乐平市| 南华县| 娄烦县| 扎兰屯市| 贵溪市| 额尔古纳市| 青阳县| 澎湖县| 永兴县| 扬中市| 嘉定区| 湛江市| 共和县| 行唐县| 新昌县|