2022-03-06 vector 底层原理以及实测

底层原理

参考

代码测试

#include <bits/stdc++.h>
using namespace std;

int main() {
    // size 和 capacity 区别
    // vector 中有三个迭代器: start finish end_of_storage
    // size = finish - start,  capacity = end_of_storage - start
    cout << "#####: size capacity" << endl;
    vector<int> vec(5, 0);
    cout << "size:" << vec.size() << endl;          // output: size:5
    cout << "capacity:" << vec.capacity() << endl;  // output: capacity:5 
    /// capacity不够,成倍扩容,再复制到新内存,销毁旧内存
    vec.push_back(1);
    cout << "size:" << vec.size() << endl;          // output: size:6   
    cout << "capacity:" << vec.capacity() << endl;  // output: capacity:10
    /// shrink_to_fit 函数请求容器降低其capacity和size匹配
    vec.shrink_to_fit();
    cout << "size:" << vec.size() << endl;          // output: size:6
    cout << "capacity:" << vec.capacity() << endl;  // output: capacity:6

    /// clear函数只是移动了finish迭代器,并没有收回内存
    /// 即只改变size,不改变capacity
    cout << "#####: clear function" << endl;
    vec.clear();
    cout << "size:" << vec.size() << endl;          // output: size:0
    cout << "capacity:" << vec.capacity() << endl;  // output: capacity:6
    /// empty函数通过判断size是否为0,来判空,其实vector内存可能还在
    cout << "empty:" << vec.empty() << endl;        // output: empty:1
    vec.shrink_to_fit();
    cout << "size:" << vec.size() << endl;          // output: size:0
    cout << "capacity:" << vec.capacity() << endl;  // output: capacity:0
    cout << "empty:" << vec.empty() << endl;        // output: empty:1

    // reserve函数和 resize函数
    cout << "#####: reserve function  resize function" << endl;
    vector<int> vec_reserve, vec_resize;
    /// reserve 函数只改变 capacity
    /// 如果当前 capacity 不够,就扩容调整; 够了,就不操作(只扩容,不缩容)
    vec_reserve.reserve(5);
    cout << "size:" << vec_reserve.size() << endl;          // output: size:0
    cout << "capacity:" << vec_reserve.capacity() << endl;  // output: capacity:5
    vec_reserve.reserve(3);
    cout << "size:" << vec_reserve.size() << endl;          // output: size:0
    cout << "capacity:" << vec_reserve.capacity() << endl;  // output: capacity:5
    /// resize 函数只改变 size
    /// 但是如果需要的size大于capacity, 则不得不改变 capacity
    vec_resize.resize(5);
    cout << "size:" << vec_resize.size() << endl;          // output: size:5
    cout << "capacity:" << vec_resize.capacity() << endl;  // output: capacity:5
    vec_resize.resize(3);
    cout << "size:" << vec_resize.size() << endl;          // output: size:3
    cout << "capacity:" << vec_resize.capacity() << endl;  // output: capacity:5
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容