std::vector扩容机制,.按1.5倍取整扩容,如下。

2020-10-10 16:40:54 浏览数 (1)

代码语言:javascript复制
#include <iostream>
#include <vector>

using namespace std;

/*
 * 结论:
 * capacity = 1, newcapacity = 2;
 * capacity > 1, newcapacity = (int)(capacity * 1.5);
 */
int main(){
    int cap = -1;
    vector<int> ints;
    for(int i = 0;i<1000000;i  ){
        ints.push_back(i);
        if( cap != ints.capacity()){
            cap = ints.capacity();
            cout << " ints.size() = " << ints.size() << "  ints.capacity() = " << cap << endl;
        }
    }
    cout << (int)(3*1.5) << endl;
    system("pause");
    return 0;
}

0 人点赞