使用stl中的 advance和 distance 方法來進行iterator的加減

來源:互聯網
上載者:User
                                   使用stl中的  advance和 distance 方法來進行iterator的加減           以前在遍曆vector的時候,經常使用iterator之間的加減來獲得元素在容器裡面的index。
         今天在進行list的 iterator加減的時候,發現不能編譯通過,後面想起list是非線性容器,不能加減。
         查了一下資料,發現stl有提供兩個iterator加減的方法:advance 和 distance
         advance是 將iterator移動,而distance是計算兩個iterator直接的距離。
        

 template<typename _InputIterator>

    inline typename
iterator_traits<_InputIterator>::difference_type

    distance(_InputIterator __first, _InputIterator __last)

    {

      // concept requirements -- taken care of in __distance

      return std::__distance(__first, __last,

    std::__iterator_category(__first));

    }

  第一個參數first,第二個參數last  

   返回的是基於 first + n  = last  ,中的 n

 也就是基於,last 是由first經過n可以到達的,注意n可能為負的。

 我第一次使用這個就是將兩個參數順序弄反了,結果返回負的n,而我這個是對應一個數位Index下標,結果導致找不到對應的index的元素。



         例子代碼如下:         
    std::vector<STableInfor>::iterator  iter_begin =  m_tableInfoList.begin();    std::vector<STableInfor>::iterator  iter_end = m_tableInfoList.end();   int   index =   distance(iter_begin,iter_end);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.