vector源码(参考STL源码--侯捷):空间分配导致迭代器失效

vector源码(参考STL源码--侯捷)-----空间分配导致迭代器失效
#include<bits/stdc++.h>
using namespace std;

int main(){
    vector<int> v(3,3);
    vector<int>::iterator it=v.begin();
    cout<<v.size()<<"  "<<v.capacity()<<endl;//3 3
    int k=0;
    while(it!=v.end())
    {
        cout<<*it<<' ';
        k++;
        ++it;
    }
    cout<<endl;
    cout<<"k: "<<k<<endl;
    v.push_back(7);
    v.push_back(8);
    v.push_back(9);
    v.push_back(5);
    cout<<v.size()<<"  "<<v.capacity()<<endl;//7 12
    while(it!=v.end())
    {
        cout<<*it<<' ';
        k++;
        ++it;
    }
    cout<<endl;
    cout<<"k: "<<k<<endl;
    return 0;
}

输出:

可以发现因为空间分配的原因,该迭代器已经失效了!!!!,详细参考 源码2 。

原文地址:https://www.cnblogs.com/ybf-yyj/p/9615621.html