vector的capacity()调用返回vector中最大能够存储的元素个数,也即在下一次需要扩充容量之前能容纳的元素个数。reserve会使容器在必要的时候增长,以便容纳制指定数目的元素。
#include <iostream> #include <vector> using namespace std; int main() { vector<int> u; cout << "Initial capaciry of u: " << u.capacity() << "\n"; for(int i = 0; i < 40; ++i) { u.push_back(i); cout<<"size is "<<u.size()<<" "; cout<<"Now capacity is :" << u.capacity() << "\n"; } return 0; }
运行环境:win7 32bit codeblocks
Initial capaciry of u: 0 size is 1 Now capacity is :1 size is 2 Now capacity is :2 size is 3 Now capacity is :4 size is 4 Now capacity is :4 size is 5 Now capacity is :8 size is 6 Now capacity is :8 size is 7 Now capacity is :8 size is 8 Now capacity is :8 size is 9 Now capacity is :16 size is 10 Now capacity is :16 size is 11 Now capacity is :16 size is 12 Now capacity is :16 size is 13 Now capacity is :16 size is 14 Now capacity is :16 size is 15 Now capacity is :16 size is 16 Now capacity is :16 size is 17 Now capacity is :32 size is 18 Now capacity is :32 size is 19 Now capacity is :32 size is 20 Now capacity is :32 size is 21 Now capacity is :32 size is 22 Now capacity is :32 size is 23 Now capacity is :32 size is 24 Now capacity is :32 size is 25 Now capacity is :32 size is 26 Now capacity is :32 size is 27 Now capacity is :32 size is 28 Now capacity is :32 size is 29 Now capacity is :32 size is 30 Now capacity is :32 size is 31 Now capacity is :32 size is 32 Now capacity is :32 size is 33 Now capacity is :64 size is 34 Now capacity is :64 size is 35 Now capacity is :64 size is 36 Now capacity is :64 size is 37 Now capacity is :64 size is 38 Now capacity is :64 size is 39 Now capacity is :64 size is 40 Now capacity is :64
vector的capacity增长方式,布布扣,bubuko.com
时间: 2024-10-06 04:13:34