2016-06-07 108 views
0

我只是在向量中的迭代器上写一个测试程序,在开始时我刚创建了一个向量并用一系列数字1-10初始化它。循环与向量中的迭代器

之后,我创建了一个迭代器“myIterator”和一个常量迭代器“iter”。我用它来显示矢量的内容。

后来我将“myIterator”分配给了“anotherVector.begin()”。所以他们指的是同样的事情。

与myIterator检查由

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

所以在第二迭代循环我刚更换 “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 

如果他们只是指向相同的地址,为什么会有这么多的差别。

回答

3

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

+0

而不是发布我自己的答案,因为你击败了我,[这里是链接'vector'迭代器失效](http://en.cppreference.com/w/cpp/container/vector#Iterator_invalidation)以供参考。 – ShadowRanger

+0

感谢它,我已经与地址运营商确认。 –

0

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

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 

输出可以根据在机器上发生变化后。

+0

如果您愿意分享,是否在示例代码中发现了明显的问题? – md5i