zoukankan      html  css  js  c++  java
  • vecor预分配内存溢出2

    vector预分配内存溢出导致原始的 迭代器 失效

    consider what happens when you add the one additional object that causes the vector to reallocate storage and move it elsewhere. The iterator’s pointer is now pointing off into nowhere:

    This illustrates the concept of iterator invalidation. Certain operations cause internal changes to a container’s underlying data, so any iterators in effect before such changes may no longer be valid afterward. 

    #include<iostream>
    #include<iterator>
    #include<vector>
    using namespace std;
    int main()
    {
        vector<int> vi(10, 0);
        ostream_iterator<int> out(cout, " ");
        vector<int>::iterator i = vi.begin();
        *i = 47;
        copy(vi.begin(), vi.end(), out);
        cout << endl;
        //force it to move memory(could also just add enough objects)
        vi.resize(vi.capacity() + 1);
        //now i points to wrong memory
        *i = 48;
        copy(vi.begin(), vi.end(), out);//no change to vi[0]
    }

  • 相关阅读:
    N皇后问题
    SDNU1349.快速幂入门
    SDNU1522.陆历川学数学
    埃氏筛
    快速幂
    string函数
    Golang介绍以及安装
    Promise解决回调地狱(多层调用问题)
    JavaScript动画相关
    ES6简单语法
  • 原文地址:https://www.cnblogs.com/learning-c/p/5702614.html
Copyright © 2011-2022 走看看