簡體   English   中英

在向量中與迭代器循環

[英]looping with iterator in a vector

我只是在vector的迭代器上編寫測試程序,一開始我只是創建了vector,並用一系列數字1-10對其進行了初始化。

之后,我創建了一個迭代器“ myIterator”和一個常量迭代器“ iter”。 我曾使用iter來顯示向量的內容。

后來我將“ myIterator”分配給“ anotherVector.begin()”。 所以他們指的是同一件事。

通過檢查

//cout << /* *myIterator << */"\t" << *(anotherVector.begin()) << endl;

所以在第二個迭代器循環中,我只是用myIterator替換了“ anotherVector.begin()”。

但這產生了不同的輸出。

代碼是:

    vector<int> anotherVector;

for(int i = 0; i < 10; i++) {
    intVector.push_back(i + 1);
    cout << anotherVector[i] << endl;
}

    cout << "anotherVector" << endl;

//*************************************
//Iterators

cout << "Iterators" << endl;

vector<int>::iterator myIterator;
vector<int>::const_iterator iter;

for(iter = anotherVector.begin(); iter != anotherVector.end(); ++iter) {
    cout << *iter << endl;
}

cout << "Another insertion" << endl;

myIterator = anotherVector.begin();

//cout << /* *myIterator << */"\t" << *(anotherVector.begin()) << endl;

myIterator[5] = 255;
anotherVector.insert(anotherVector.begin(),200);

//for(iter = myIterator; iter != anotherVector.end(); ++iter) {
    //cout << *iter << endl;
//}

for(iter = anotherVector.begin(); iter != anotherVector.end(); ++iter) {
    cout << *iter << endl;
}

輸出使用

for(iter = anotherVector.begin(); iter != anotherVector.end(); ++iter) {
    cout << *iter << endl;
}

給出:

    Iterators
    1
    2
    3   
    4
    5
    6
    7
    8
    9
    10
    Another insertion
    200
    1
    2
    3
    4
    5
    255
    7
    8
    9
    10

和輸出使用

for(iter = myIterator; iter != anotherVector.end(); ++iter) {
    cout << *iter << endl;
}

給出:

    Iterators
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    Another insertion
    0
    0
    3
    4
    5
    255
    7
    8
    9
    10
    81
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    0
    0
    0
    0
    0
    0
    0
    0
    97
    0
    200
    1
    2
    3
    4
    5
    255
    7
    8
    9
    10

如果他們只是指向相同的地址,為什么會有如此大的差異。

insertmyIterator不再有效。 這是因為插入std::vector會導致向量重新分配,因此,先前迭代器指向的地址可能未指向重新分配的向量的地址空間。

我剛剛發現了我的錯誤,但是您可以檢查迭代器地址的位置是否有變化。

myIterator = anotherVector.begin();

    cout << "test line\t" << &(*myIterator) << "\t" << &(*(anotherVector.begin())) << endl;

    //myIterator[5] = 255;
    anotherVector.insert(anotherVector.begin(),200);

    cout << "test line\t" << &(*myIterator) << "\t" << &(*(anotherVector.begin())) << endl;

這給出了輸出:

插入前

test line   0x92f070    0x92f070

插入后

test line   0x92f070    0x92f0f0

輸出可能會因機器而異。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM