矢量大小和容量
矢量大小只是矢量中元素的数量:
-
size()
成员函数查询当前向量大小。如果 size 为 0,方便empty()
函数返回true
:vector<int> v = { 1, 2, 3 }; // size is 3 const vector<int>::size_type size = v.size(); cout << size << endl; // prints 3 cout << boolalpha << v.empty() << endl; // prints false
-
默认构造的向量以 0 开头:
vector<int> v; // size is 0 cout << v.size() << endl; // prints 0
-
将
N
元素添加到向量会增加N
的大小 (例如,通过push_back()
,insert()
或resize()
函数)。 -
从矢量中删除
N
元素会减少N
的大小 (例如,通过pop_back()
,erase()
或clear()
函数)。 -
Vector 对其大小有一个特定于实现的上限,但在到达它之前可能会耗尽 RAM:
vector<int> v; const vector<int>::size_type max_size = v.max_size(); cout << max_size << endl; // prints some large number v.resize( max_size ); // probably won't work v.push_back( 1 ); // definitely won't work
常见错误: 尺寸不一定(甚至通常)int
:
// !!!bad!!!evil!!!
vector<int> v_bad( N, 1 ); // constructs large N size vector
for( int i = 0; i < v_bad.size(); ++i ) { // size is not supposed to be int!
do_something( v_bad[i] );
}
矢量容量与大小不同。虽然大小只是向量当前有多少元素,但容量是它分配了多少元素/保留内存。这很有用,因为太大的太频繁(重新)分配可能很昂贵。
-
capacity()
成员函数查询当前向量容量。容量始终大于或等于大小 :vector<int> v = { 1, 2, 3 }; // size is 3, capacity is >= 3 const vector<int>::size_type capacity = v.capacity(); cout << capacity << endl; // prints number >= 3
-
你可以通过
reserve( N )
函数手动预留容量(它将矢量容量改为N
):// !!!bad!!!evil!!! vector<int> v_bad; for( int i = 0; i < 10000; ++i ) { v_bad.push_back( i ); // possibly lot of reallocations } // good vector<int> v_good; v_good.reserve( 10000 ); // good! only one allocation for( int i = 0; i < 10000; ++i ) { v_good.push_back( i ); // no allocations needed anymore }
-
你可以请求
shrink_to_fit()
释放多余的容量(但实施不必遵守你的要求)。这对于节省使用的内存很有用:vector<int> v = { 1, 2, 3, 4, 5 }; // size is 5, assume capacity is 6 v.shrink_to_fit(); // capacity is 5 (or possibly still 6) cout << boolalpha << v.capacity() == v.size() << endl; // prints likely true (but possibly false)
Vector 会自动部分管理容量,当你添加元素时,它可能会决定增长。实施者喜欢使用 2 或 1.5 作为增长因子(黄金比率将是理想值 - 但由于是有理数而不切实际)。另一方面,矢量通常不会自动缩小。例如:
vector<int> v; // capacity is possibly (but not guaranteed) to be 0
v.push_back( 1 ); // capacity is some starter value, likely 1
v.clear(); // size is 0 but capacity is still same as before!
v = { 1, 2, 3, 4 }; // size is 4, and lets assume capacity is 4.
v.push_back( 5 ); // capacity grows - let's assume it grows to 6 (1.5 factor)
v.push_back( 6 ); // no change in capacity
v.push_back( 7 ); // capacity grows - let's assume it grows to 9 (1.5 factor)
// and so on
v.pop_back(); v.pop_back(); v.pop_back(); v.pop_back(); // capacity stays the same