【问题标题】:looping with iterator in a vector在向量中使用迭代器循环
【发布时间】:2016-10-06 18:53:56
【问题描述】:

我只是在向量中的迭代器上编写一个测试程序,一开始我刚刚创建了一个向量并用一系列数字 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

如果它们只是指向同一个地址,为什么会有如此大的差异。

【问题讨论】:

    标签: c++ loops vector reference iterator


    【解决方案1】:

    在您的insert 之后,myIterator 不再一定有效。这是因为插入std::vector 会导致向量重新分配,因此之前的迭代器指向的地址可能不会指向重新分配的向量的地址空间。

    【讨论】:

    【解决方案2】:

    我刚刚发现了我的错误,但您可以检查迭代器地址位置的变化。

    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
    

    输出可能因机器而异。

    【讨论】:

    • 如果您愿意分享,您发现的问题在示例代码中是否明显?
    猜你喜欢
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多