vector的reserve(),resize(),capacity()
阿新 • • 發佈:2019-02-06
1:vetor<int> a;
a.reserve(100);
代表預留空間是100,capacity()的返回值也是就100;
vector功能和陣列相似,capacity類似於我們通常預設定的陣列的最大元素個數,如a[10],代表的就是a陣列最多10個元素;
程式碼如下:
// vector::reserve
#include <iostream>
#include <vector>
int main ()
{
std::vector<int>::size_type sz;
std::vector<int> foo;
sz = foo.capacity();
std::cout << "making foo grow:\n" ;
for (int i=0; i<100; ++i) {
foo.push_back(i);
if (sz!=foo.capacity()) {
sz = foo.capacity();
std::cout << "capacity changed: " << sz << '\n';
}
}
std::vector<int> bar;
sz = bar.capacity();
bar.reserve(100); // this is the only difference with foo above
std::cout << "making bar grow:\n";
for (int i=0; i<100; ++i) {
bar.push_back(i);
if (sz!=bar.capacity()) {
sz = bar.capacity();
std::cout << "capacity changed: " << sz << '\n';
}
}
return 0;
}
輸出的結果:
making foo grow:
capacity changed: 1
capacity changed: 2
capacity changed: 4
capacity changed: 8
capacity changed: 16
capacity changed: 32
capacity changed: 64
capacity changed: 128
making bar grow:
capacity changed: 100
2:a.resize(n,m) or a.resize(n)
n代表的就是重新設定vector元素的多少
n大於你之前的size()時,會加上 n-size() 個元素值為m的元素(若m沒有,就設定為預設值0);
n小於你之前的size()時,會刪除 下標為 n~size()-1 的元素。