Why does this vector iterator not become invalidated?

I've read a few posts concerning iterator invalidation, and it seems that inserts that require a vector reallocation would invalidate iterators. Also shouldn't erases in the middle of the vector cause an invalidation?

I don't have a clear understanding of this, not sure why using these iterators after resizes and erases from begin, middle, and end doesn't break them:

#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char** argv) {

    vector<int> v;
    v.reserve(10);

    for (int i = 0; i < 10; i++)
        v.push_back(i);

    for (auto x = v.begin(); x != v.end(); x++) {
        cout << *x << endl;
    }

    cout << endl << "RESIZE" << endl << endl;

    for (int i = 10; i < 20; i++)
        v.push_back(i);

    for (auto x = v.begin(); x != v.end(); x++) {
        cout << *x << endl;
    }

    cout << endl << "RESIZE 2" << endl << endl;

    for (int i = 20; i < 200; i++)
        v.push_back(i);

    for (auto x = v.begin(); x != v.end(); x++) {
        cout << *x << endl;
    }

    cout << endl << "REMOVES" << endl << endl;

    v.erase(v.begin());
    v.pop_back();
    v.erase(v.begin() + 17);

    for (auto x = v.begin(); x != v.end(); x++) {
        cout << *x << endl;
    }

    return 0;
}

Note that calling begin() or end() will always provide a sane iterator

However something like:

std:vector<int> v;
....

std::vector<int>::iterator i=v.begin();
v.erase(i);
std::cout << *i << std::endl;  // i iterator was invalidated by erasing it
                               // trying to access it or increment it is undefined behaviour.
std::cout << *v.begin() << std::endl;  // begin() provides always a sane iterator.

In your code, always when iterators are reused, there was no intervening modification of the vector, so no invalidation.

Iterators may be invalidated on resizing and inserting. Erasing only invalidates iterators at or after the erased element.

At least, those are the paraphrased rules for std::vector .

链接地址: http://www.djcxy.com/p/73328.html

上一篇: 迭代器失效规则是否意味着线程安全?

下一篇: 为什么这个向量迭代器不会失效?