C++ 向量的 size() 和 capacity()

size() and capacity() of c++ vectors

我刚刚开始使用 C++ 的标准库,我首先开始的是 std::vector。我对向量中的 capacity() 有点困惑。我知道在每个 push_back() 之后,向量的 capacity 以指数幂变化,但在下面的输出中 capacity 有时保持相同的值,即使在插入之后也是如此。有人可以向我解释一下内部工作吗?

#include<iostream>
#include<vector>

using namespace std;

int main(){
    vector<int> v;
    int capacity=v.capacity();
    cout<<"Capacity before push_back(): "<<capacity<<endl;
    for(int i=0;i<10;i++){
        v.push_back(i);
        cout<<"Capacity: "<<v.capacity()<<endl;
        
    }
    for(auto j=v.begin();j!=v.end();j++){
        cout<<*j<<endl;
    }
     
    cout<<"Size of vector: "<<v.size()<<endl;
    cout<<"Final Capacity of vector: "<<v.capacity()<<endl;
    
    return 0;
}

输出:

Capacity before push_back(): 0
Capacity: 1
Capacity: 2
Capacity: 4
Capacity: 4
Capacity: 8
Capacity: 8
Capacity: 8
Capacity: 8
Capacity: 16
Capacity: 16
0
1
2
3
4
5
6
7
8
9
Size of vector: 10
Final Capacity of vector: 16

I know that after each push_back() the capacity of the vector changes in exponential powers but in the above OUTPUT the capacity is still remaining same sometimes even after insertion.

当capacity大于插入后的size时,capacity不需要,保证不变。

此策略允许顺序推回具有恒定的复杂性(摊销)。

来自 Vector[强调]

The storage of the vector is handled automatically, being expanded and contracted as needed. Vectors usually occupy more space than static arrays, because more memory is allocated to handle future growth. This way a vector does not need to reallocate each time an element is inserted, but only when the additional memory is exhausted. The total amount of allocated memory can be queried using capacity() function. Extra memory can be returned to the system via a call to shrink_to_fit(). (since C++11)

I know that after each push_back(), the capacity of the vector changes in exponential powers, but in the below output the capacity remains the same value sometimes, even after insertions.

这就是你的误会所在。向量的 CAPACITY 不会在 every 插入时增加,它的 SIZE 会增加。 CAPACITY 在插入导致 SIZE 增加到超过当前 CAPACITY 时增长,或者如果您明确通过调用 reserve() 方法请求增加 CAPACITY