The difference between capacity() and size() in C++ vector

1 Introduction to capacity() and size()

size refers to the number of elements currently owned by the container, and
capacity refers to the total number of elements that the container can store before new storage space must be allocated.

  • likevector<int> ivect,ivect.reserve(10),ivect.size()=0,ivect.capacity()=10
    • When inserting elements into ivect, as long as does not exceed 10, the capacity remains unchanged, and the size is the element you inserted. number.
    • WhenInput 10th numberWhencapacity=size=10,
    • At the timeInput the 11th numberWhen the container重新分配存储空间:ivect.capacity()=20,而ivect.size()=11,
    • i.e. If the container reallocates space, it will be allocated twice the existing space to ensure the efficiency of the vector.
int main()
{
    
    
    std::vector<int> v1;
    v1.reserve(10);//容器预留 len 个元素长度
    cout << "v1初始 size 和 capacity大小:\n " << "\tv1_size : "<<v1.size() << "\t v1_capacity: " << v1.capacity() <<endl << endl;

    // 添加元素
    cout << "v1c中插入元素后 size 和 capacity大小: " << v1.size() << endl << endl;
    for (int i = 0; i < 13; i++)
    {
    
    
        v1.push_back(i);
        cout << "\tv1_size: " << v1.size() << "\tv1_capacity: " << v1.capacity() << endl;
    }

    return 0;
}

Insert image description here

See the result on the top surface,
NowInput the 11th numberWhen the container并未上面所说ivect.capacity()=20. and,重新分配存储空间ivect.size()=11
ivect.capacity()=15

2 After the vector is full, capacity() will automatically expand to 2 times its original size?


In order to verify the statement that the function was expanded by 2 times, I found other information.


There is a saying:When the vector is full, it will automatically expand to twice its original size

The vector has a rainy day mechanism. When it is full, it will automatically expand to twice its original size.

(Improve efficiency and avoid frequent "configure new space - move data - release old space")

Insert image description here

The author ran it on qt, I ran it on VS, and it aborted.“vector迭代器不兼容”

int main() {
    
    

    vector<int> v;//最初容器没有元素,容量为空
    cout << "容量" << v.capacity() << endl;

    vector<int>::iterator it ;
    int i = 0;
    int count = 0;

    for ( i = 0; i < 1000; i++) {
    
    
        v.push_back(i);//插入第一个元素,开辟1空间;插入第二个元素,开辟2空间;插入第三个元素,开辟4空间。。。每次二倍
        if (it != v.begin()) {
    
     //如果不相等,说明又开辟了新空间,v.begin指向新空间的开头;
            count++;
            cout <<"开辟空间容量: " << v.capacity() << endl;
            it = v.begin();//it记录当前空间的开头
       }
    }
    return 0;
}

Insert image description here

Guess you like

Origin blog.csdn.net/m0_51233386/article/details/134401764