顯示廣告
隱藏 ✕
看板 Programming
作者 abc1231qa(替咖)
標題 [C++ ] 什麼是iterator
時間 2010年01月28日 Thu. PM 11:14:07


大一的時候

每次都游泳課完直接去上程式設計

結果講iterator的時候我睡著了

一直到現在我是搞不懂這到底是啥鬼...........


隨便GOOGLE了一下

http://squall.cs.ntou.edu.tw/cpp/93spring/lab04/vectorIterator.html

Iterator 的用法

iterator 使用起來像是一個指標, 可以用 ++, <, >, =, *, -> 等等運算去移動, 擷取資料, 你可以抽象地把它想像成是指標, 目前內部實作也是指標, 但是你不要去把它真的轉型為指標,

    DataRecord *ptr = (DataRecord *)iter;
   

compiler 廠商並不保證它以後的實作一定是指標

另外參考一下下面的範例程式, 這個程式告訴你你可以刪除 vector 裡面的成員, 刪除後 vector 物件會自動重新排過

// cl -GX testVectorErase.cpp

#include <iostream>
#include <vector>
using namespace std;

void main()
{
    vector<int> data;
    int i;
    for (i=0; i<10; i++)
    {
        data.push_back(i+1);
//        if (i%2 == 1) data.erase(&data[i-1]);  
         // cause illegal access error in memory
    }

    for (i=0; i<data.size(); i++)
        cout << "(" << i << "," << data[i] << ") ";
    cout << endl;
   
    data.erase(&data[0]);
//    data.erase(&data[9]);  
// cause illegal access error
// i.e. erase(&data[0]) would move all members ahead one
//      position virtually

    data.erase(&data[8]);

    for (i=0; i<data.size(); i++)
        cout << "(" << i << "," << data[i] << ") ";
    cout << endl;

    vector<int>::iterator iter;
    int sum=0;
    for (i=0; i<data.size(); i++)
        sum += data[i];
    cout << "using array index " << sum << endl;

    sum = 0;
    for (iter=data.begin(); iter<data.end(); iter++)
        sum += *iter;
    cout << "using iter " << sum << endl;
}
   

上面這個程式的輸出如下:

F:\>testVectorErase
(0,1) (1,2) (2,3) (3,4) (4,5) (5,6) (6,7) (7,8) (8,9) (9,10)
(0,2) (1,3) (2,4) (3,5) (4,6) (5,7) (6,8) (7,9)
using array index 44
using iter 44
   


--
※ 來源: DISP BBS (http://disp.twbbs.org)
※ 作者: abc1231qa  來自: 219.69.80.39  時間: 2010-01-28 23:14:07
※ 看板: Programming 文章推薦值: 3 目前人氣: 0 累積人氣: 11023 
分享網址: 複製 已複製
( ̄︶ ̄)b jason132454 說讚!
1樓 時間: 2010-01-28 23:14:41 (台灣)
  01-28 23:14 TW
我承認我有看沒有懂 這不就只是vector嗎?
2樓 時間: 2010-01-28 23:44:27 (台灣)
  01-28 23:44 TW
me too   程式被當過
3樓 時間: 2010-01-29 00:06:27 (台灣)
  01-29 00:06 TW
不 我自認沒學好還是拿A+了...............
4樓 時間: 2010-01-29 01:03:08 (台灣)
  01-29 01:03 TW
樓上是天才   = =
5樓 時間: 2010-01-29 07:40:59 (台灣)
  01-29 07:40 TW
為什麼看起來真的像是vector...
6樓 時間: 2010-02-06 03:25:01 (台灣)
  02-06 03:25 TW
我都用foreach的語法 用起來比較方便0.0
7樓 時間: 2010-04-01 00:28:49 (台灣)
  04-01 00:28 TW
foreach其實就是包裝後的iterator
r)回覆 e)編輯 d)刪除 M)收藏 ^x)轉錄 同主題: =)首篇 [)上篇 ])下篇